diff --git a/.gitignore b/.gitignore index ce179b055b..7974b169d6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ .timestamp .pyenv .virtualenv -gen/ +gen/doc/ *.go *.pyc **target/ diff --git a/etc/api/shared.yaml b/etc/api/shared.yaml index de09e56e34..f40a09a5cd 100644 --- a/etc/api/shared.yaml +++ b/etc/api/shared.yaml @@ -28,7 +28,7 @@ api: - source: lib.rs output_dir: src cargo: - build_version: "0.0.1" + build_version: "0.1.0" repo_base_url: https://github.com/Byron/google-apis-rs doc_base_url: http://byron.github.io/google-apis-rs authors: diff --git a/gen/adexchangebuyer1d3/Cargo.toml b/gen/adexchangebuyer1d3/Cargo.toml new file mode 100644 index 0000000000..f98464e4b6 --- /dev/null +++ b/gen/adexchangebuyer1d3/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adexchangebuyer1d3" +version = "0.1.0+20150218" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Ad Exchange Buyer (protocol v1.3)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d3" +homepage = "https://developers.google.com/ad-exchange/buyer-rest" +documentation = "http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3" +license = "MIT" +keywords = ["adexchangebuyer", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/adexchangebuyer1d3/LICENSE.md b/gen/adexchangebuyer1d3/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adexchangebuyer1d3/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/adexchangebuyer1d3/README.md b/gen/adexchangebuyer1d3/README.md new file mode 100644 index 0000000000..2e55a38baf --- /dev/null +++ b/gen/adexchangebuyer1d3/README.md @@ -0,0 +1,184 @@ + +The `google-adexchangebuyer1d3` library allows access to all features of the *Google Ad Exchange Buyer* service. + +This documentation was generated from *Ad Exchange Buyer* crate version *0.1.0+20150218*, where *20150218* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Ad Exchange Buyer* *v1d3* API can be found at the +[official documentation site](https://developers.google.com/ad-exchange/buyer-rest). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AdExchangeBuyer.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.Account.html) + * [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AccountUpdateCall.html) +* [billing info](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BillingInfo.html) + * [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BillingInfoGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BillingInfoListCall.html) +* [budget](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.Budget.html) + * [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BudgetGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BudgetPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.BudgetUpdateCall.html) +* [creatives](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.Creative.html) + * [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.CreativeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.CreativeInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.CreativeListCall.html) +* [direct deals](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.DirectDeal.html) + * [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.DirectDealGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.DirectDealListCall.html) +* [performance report](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PerformanceReport.html) + * [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PerformanceReportListCall.html) +* [pretargeting config](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfig.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.PretargetingConfigUpdateCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/struct.AdExchangeBuyer.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.pretargeting_config().insert(...).doit() +let r = hub.pretargeting_config().patch(...).doit() +let r = hub.pretargeting_config().get(...).doit() +let r = hub.pretargeting_config().update(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-adexchangebuyer1d3 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +use adexchangebuyer1d3::PretargetingConfig; +use adexchangebuyer1d3::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use adexchangebuyer1d3::AdExchangeBuyer; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: PretargetingConfig = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.pretargeting_config().patch(&req, "accountId", "configId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **adexchangebuyer1d3** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/adexchangebuyer1d3/src/cmn.rs b/gen/adexchangebuyer1d3/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/adexchangebuyer1d3/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/adexchangebuyer1d3/src/lib.rs b/gen/adexchangebuyer1d3/src/lib.rs new file mode 100644 index 0000000000..e39ec436e8 --- /dev/null +++ b/gen/adexchangebuyer1d3/src/lib.rs @@ -0,0 +1,6651 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Ad Exchange Buyer* crate version *0.1.0+20150218*, where *20150218* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Ad Exchange Buyer* *v1d3* API can be found at the +//! [official documentation site](https://developers.google.com/ad-exchange/buyer-rest). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d3). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AdExchangeBuyer.html) ... +//! +//! * [accounts](struct.Account.html) +//! * [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*patch*](struct.AccountPatchCall.html) and [*update*](struct.AccountUpdateCall.html) +//! * [billing info](struct.BillingInfo.html) +//! * [*get*](struct.BillingInfoGetCall.html) and [*list*](struct.BillingInfoListCall.html) +//! * [budget](struct.Budget.html) +//! * [*get*](struct.BudgetGetCall.html), [*patch*](struct.BudgetPatchCall.html) and [*update*](struct.BudgetUpdateCall.html) +//! * [creatives](struct.Creative.html) +//! * [*get*](struct.CreativeGetCall.html), [*insert*](struct.CreativeInsertCall.html) and [*list*](struct.CreativeListCall.html) +//! * [direct deals](struct.DirectDeal.html) +//! * [*get*](struct.DirectDealGetCall.html) and [*list*](struct.DirectDealListCall.html) +//! * [performance report](struct.PerformanceReport.html) +//! * [*list*](struct.PerformanceReportListCall.html) +//! * [pretargeting config](struct.PretargetingConfig.html) +//! * [*delete*](struct.PretargetingConfigDeleteCall.html), [*get*](struct.PretargetingConfigGetCall.html), [*insert*](struct.PretargetingConfigInsertCall.html), [*list*](struct.PretargetingConfigListCall.html), [*patch*](struct.PretargetingConfigPatchCall.html) and [*update*](struct.PretargetingConfigUpdateCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AdExchangeBuyer.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.pretargeting_config().insert(...).doit() +//! let r = hub.pretargeting_config().patch(...).doit() +//! let r = hub.pretargeting_config().get(...).doit() +//! let r = hub.pretargeting_config().update(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-adexchangebuyer1d3 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +//! use adexchangebuyer1d3::PretargetingConfig; +//! use adexchangebuyer1d3::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use adexchangebuyer1d3::AdExchangeBuyer; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: PretargetingConfig = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.pretargeting_config().patch(&req, "accountId", "configId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your Ad Exchange buyer account configuration + AdexchangeBuyer, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::AdexchangeBuyer => "https://www.googleapis.com/auth/adexchange.buyer", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::AdexchangeBuyer + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AdExchangeBuyer related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::PretargetingConfig; +/// use adexchangebuyer1d3::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PretargetingConfig = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().patch(&req, "accountId", "configId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AdExchangeBuyer { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AdExchangeBuyer {} + +impl<'a, C, NC, A> AdExchangeBuyer + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AdExchangeBuyer { + AdExchangeBuyer { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + pub fn billing_info(&'a self) -> BillingInfoMethods<'a, C, NC, A> { + BillingInfoMethods { hub: &self } + } + pub fn budget(&'a self) -> BudgetMethods<'a, C, NC, A> { + BudgetMethods { hub: &self } + } + pub fn creatives(&'a self) -> CreativeMethods<'a, C, NC, A> { + CreativeMethods { hub: &self } + } + pub fn direct_deals(&'a self) -> DirectDealMethods<'a, C, NC, A> { + DirectDealMethods { hub: &self } + } + pub fn performance_report(&'a self) -> PerformanceReportMethods<'a, C, NC, A> { + PerformanceReportMethods { hub: &self } + } + pub fn pretargeting_config(&'a self) -> PretargetingConfigMethods<'a, C, NC, A> { + PretargetingConfigMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Requests containing any of these placements will not match. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PretargetingConfigExcludedPlacements { + /// The value of the placement. Interpretation depends on the placement type, e.g. URL for a site placement, channel name for a channel placement, app id for a mobile app placement. + pub token: String, + /// The type of the placement. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for PretargetingConfigExcludedPlacements {} +impl Part for PretargetingConfigExcludedPlacements {} + + +/// The reasons for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeDisapprovalReasons { + /// The categorized reason for disapproval. + pub reason: String, + /// Additional details about the reason for disapproval. + pub details: Vec, +} + +impl NestedType for CreativeDisapprovalReasons {} +impl Part for CreativeDisapprovalReasons {} + + +/// Configuration data for an Ad Exchange buyer account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update accounts](struct.AccountUpdateCall.html) (request|response) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [patch accounts](struct.AccountPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Account { + /// Resource type. + pub kind: Option, + /// The sum of all bidderLocation.maximumQps values cannot exceed this. Please contact your technical account manager if you need to change this. + #[serde(alias="maximumTotalQps")] + pub maximum_total_qps: Option, + /// The maximum number of active creatives that an account can have, where a creative is active if it was inserted or bid with in the last 30 days. Please contact your technical account manager if you need to change this. + #[serde(alias="maximumActiveCreatives")] + pub maximum_active_creatives: Option, + /// Your bidder locations that have distinct URLs. + #[serde(alias="bidderLocation")] + pub bidder_location: Option>, + /// The nid parameter value used in cookie match requests. Please contact your technical account manager if you need to change this. + #[serde(alias="cookieMatchingNid")] + pub cookie_matching_nid: Option, + /// The number of creatives that this account inserted or bid with in the last 30 days. + #[serde(alias="numberActiveCreatives")] + pub number_active_creatives: Option, + /// Account id. + pub id: Option, + /// The base URL used in cookie match requests. + #[serde(alias="cookieMatchingUrl")] + pub cookie_matching_url: Option, +} + +impl RequestValue for Account {} +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list pretargeting config](struct.PretargetingConfigListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PretargetingConfigList { + /// A list of pretargeting configs + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for PretargetingConfigList {} + + +/// The filtering reasons for the creative. If this feature is not enabled, please ask your technical account manager. Read-only. This field should not be set in requests. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeFilteringReasons { + /// The date in ISO 8601 format for the data. The data is collected from 00:00:00 to 23:59:59 in PST. + pub date: String, + /// The filtering reasons. + pub reasons: Vec, +} + +impl NestedType for CreativeFilteringReasons {} +impl Part for CreativeFilteringReasons {} + + +/// The configuration data for an Ad Exchange billing info. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get billing info](struct.BillingInfoGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BillingInfo { + /// Resource type. + pub kind: String, + /// A list of adgroup IDs associated with this particular account. These IDs may show up as part of a realtime bidding BidRequest, which indicates a bid request for this account. + #[serde(alias="billingId")] + pub billing_id: Vec, + /// Account id. + #[serde(alias="accountId")] + pub account_id: i32, + /// Account name. + #[serde(alias="accountName")] + pub account_name: String, +} + +impl ResponseResult for BillingInfo {} + + +/// A direct deals feed lists Direct Deals the Ad Exchange buyer account has access to. This includes direct deals set up for the buyer account as well as its merged stream seats. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list direct deals](struct.DirectDealListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectDealsList { + /// Resource type. + pub kind: String, + /// A list of direct deals relevant for your account. + #[serde(alias="directDeals")] + pub direct_deals: Vec, +} + +impl ResponseResult for DirectDealsList {} + + +/// An account feed lists Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single buyer account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsList { + /// A list of accounts. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for AccountsList {} + + +/// The creatives feed lists the active creatives for the Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single creative. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creatives](struct.CreativeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CreativesList { + /// Continuation token used to page through creatives. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of creatives. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for CreativesList {} + + +/// The configuration data for Ad Exchange RTB - Budget API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch budget](struct.BudgetPatchCall.html) (request|response) +/// * [update budget](struct.BudgetUpdateCall.html) (request|response) +/// * [get budget](struct.BudgetGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Budget { + /// The billing id to determine which adgroup to provide budget information for. This is required for get and update requests. + #[serde(alias="billingId")] + pub billing_id: Option, + /// The kind of the resource, i.e. "adexchangebuyer#budget". + pub kind: Option, + /// The budget amount to apply for the billingId provided. This is required for update requests. + #[serde(alias="budgetAmount")] + pub budget_amount: Option, + /// The currency code for the buyer. This cannot be altered here. + #[serde(alias="currencyCode")] + pub currency_code: Option, + /// The unique id that describes this item. + pub id: Option, + /// The id of the account. This is required for get and update requests. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for Budget {} +impl ResponseResult for Budget {} + + +/// A creative and its classification data. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert creatives](struct.CreativeInsertCall.html) (request|response) +/// * [list creatives](struct.CreativeListCall.html) (none) +/// * [get creatives](struct.CreativeGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Creative { + /// Detected product categories, if any. Read-only. This field should not be set in requests. + #[serde(alias="productCategories")] + pub product_categories: Option>, + /// Creative serving status. Read-only. This field should not be set in requests. + pub status: Option, + /// The agency id for this creative. + #[serde(alias="agencyId")] + pub agency_id: Option, + /// All attributes for the ads that may be shown from this snippet. + pub attribute: Option>, + /// Ad height. + pub height: Option, + /// The name of the company being advertised in the creative. + #[serde(alias="advertiserName")] + pub advertiser_name: Option, + /// The HTML snippet that displays the ad when inserted in the web page. If set, videoURL should not be set. + #[serde(alias="HTMLSnippet")] + pub html_snippet: Option, + /// A buyer-specific id identifying the creative in this ad. + #[serde(alias="buyerCreativeId")] + pub buyer_creative_id: Option, + /// Account id. + #[serde(alias="accountId")] + pub account_id: Option, + /// Detected advertiser id, if any. Read-only. This field should not be set in requests. + #[serde(alias="advertiserId")] + pub advertiser_id: Option>, + /// Resource type. + pub kind: Option, + /// The url to fetch a video ad. If set, HTMLSnippet should not be set. + #[serde(alias="videoURL")] + pub video_url: Option, + /// The set of destination urls for the snippet. + #[serde(alias="clickThroughUrl")] + pub click_through_url: Option>, + /// Shows any corrections that were applied to this creative. Read-only. This field should not be set in requests. + pub corrections: Option>, + /// Ad width. + pub width: Option, + /// All restricted categories for the ads that may be shown from this snippet. + #[serde(alias="restrictedCategories")] + pub restricted_categories: Option>, + /// All vendor types for the ads that may be shown from this snippet. + #[serde(alias="vendorType")] + pub vendor_type: Option>, + /// The filtering reasons for the creative. If this feature is not enabled, please ask your technical account manager. Read-only. This field should not be set in requests. + #[serde(alias="filteringReasons")] + pub filtering_reasons: Option, + /// The reasons for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests. + #[serde(alias="disapprovalReasons")] + pub disapproval_reasons: Option>, + /// Detected sensitive categories, if any. Read-only. This field should not be set in requests. + #[serde(alias="sensitiveCategories")] + pub sensitive_categories: Option>, +} + +impl RequestValue for Creative {} +impl Resource for Creative {} +impl ResponseResult for Creative {} + + +/// The configuration data for an Ad Exchange performance report list. https://sites.google.com/a/google.com/adx-integration/Home/engineering/binary-releases/rtb-api-release https://cs.corp.google.com/#piper///depot/google3/contentads/adx/tools/rtb_api/adxrtb.py +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list performance report](struct.PerformanceReportListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PerformanceReportList { + /// Resource type. + pub kind: String, + /// A list of performance reports relevant for the account. + #[serde(alias="performanceReport")] + pub performance_report: Vec, +} + +impl ResponseResult for PerformanceReportList {} + + +/// The filtering reasons. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeFilteringReasonsReasons { + /// The number of times the creative was filtered for the status. The count is aggregated across all publishers on the exchange. + #[serde(alias="filteringCount")] + pub filtering_count: i64, + /// The filtering status code. Please refer to the creative-status-codes.txt file for different statuses. + #[serde(alias="filteringStatus")] + pub filtering_status: i32, +} + +impl NestedType for CreativeFilteringReasonsReasons {} +impl Part for CreativeFilteringReasonsReasons {} + + +/// Requests containing any of these placements will match. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PretargetingConfigPlacements { + /// The value of the placement. Interpretation depends on the placement type, e.g. URL for a site placement, channel name for a channel placement, app id for a mobile app placement. + pub token: String, + /// The type of the placement. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for PretargetingConfigPlacements {} +impl Part for PretargetingConfigPlacements {} + + +/// Requests which allow one of these (width, height) pairs will match. All pairs must be supported ad dimensions. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PretargetingConfigDimensions { + /// Width in pixels. + pub width: String, + /// Height in pixels. + pub height: String, +} + +impl NestedType for PretargetingConfigDimensions {} +impl Part for PretargetingConfigDimensions {} + + +/// The configuration data for an Ad Exchange performance report list. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PerformanceReport { + /// Average QPS for cookie matcher operations. + #[serde(alias="cookieMatcherStatusRate")] + pub cookie_matcher_status_rate: Vec, + /// Rate of various prefiltering statuses per match. Please refer to the callout-status-codes.txt file for different statuses. + #[serde(alias="calloutStatusRate")] + pub callout_status_rate: Vec, + /// Average QPS for hosted match operations. + #[serde(alias="hostedMatchStatusRate")] + pub hosted_match_status_rate: Vec, + /// The unix timestamp of the starting time of this performance data. + pub timestamp: String, + /// The 50th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(alias="latency50thPercentile")] + pub latency50th_percentile: f64, + /// The 85th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(alias="latency85thPercentile")] + pub latency85th_percentile: f64, + /// Average QPS for pixel match responses from clients. + #[serde(alias="pixelMatchResponses")] + pub pixel_match_responses: f64, + /// Rate of ads with a given status. Please refer to the creative-status-codes.txt file for different statuses. + #[serde(alias="creativeStatusRate")] + pub creative_status_rate: Vec, + /// The 95th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(alias="latency95thPercentile")] + pub latency95th_percentile: f64, + /// Rate of various quota account statuses per quota check. + #[serde(alias="noQuotaInRegion")] + pub no_quota_in_region: f64, + /// Resource type. + pub kind: String, + /// The trading location of this data. + pub region: String, + /// The configured quota limits for this account. + #[serde(alias="quotaConfiguredLimit")] + pub quota_configured_limit: f64, + /// Rate of various quota account statuses per quota check. + #[serde(alias="outOfQuota")] + pub out_of_quota: f64, + /// The throttled quota limits for this account. + #[serde(alias="quotaThrottledLimit")] + pub quota_throttled_limit: f64, + /// Average QPS for pixel match requests from clients. + #[serde(alias="pixelMatchRequests")] + pub pixel_match_requests: f64, +} + +impl Part for PerformanceReport {} + + +/// Shows any corrections that were applied to this creative. Read-only. This field should not be set in requests. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeCorrections { + /// The type of correction that was applied to the creative. + pub reason: String, + /// Additional details about the correction. + pub details: Vec, +} + +impl NestedType for CreativeCorrections {} +impl Part for CreativeCorrections {} + + +/// A billing info feed lists Billing Info the Ad Exchange buyer account has access to. Each entry in the feed corresponds to a single billing info. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list billing info](struct.BillingInfoListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BillingInfoList { + /// A list of billing info relevant for your account. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for BillingInfoList {} + + +/// The configuration data for an Ad Exchange direct deal. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get direct deals](struct.DirectDealGetCall.html) (response) +/// * [list direct deals](struct.DirectDealListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectDeal { + /// The name of the advertiser this deal is for. + pub advertiser: String, + /// Resource type. + pub kind: String, + /// Deal name. + pub name: String, + /// The currency code that applies to the fixed_cpm value. If not set then assumed to be USD. + #[serde(alias="currencyCode")] + pub currency_code: String, + /// The account id of the buyer this deal is for. + #[serde(alias="accountId")] + pub account_id: i32, + /// The fixed price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the fixed price tier of buying (highest priority, pay exactly the configured fixed price). + #[serde(alias="fixedCpm")] + pub fixed_cpm: String, + /// Start time for when this deal becomes active. If not set then this deal is active immediately upon creation. In seconds since the epoch. + #[serde(alias="startTime")] + pub start_time: String, + /// If true, the publisher has opted to have their blocks ignored when a creative is bid with for this deal. + #[serde(alias="publisherBlocksOverriden")] + pub publisher_blocks_overriden: bool, + /// End time for when this deal stops being active. If not set then this deal is valid until manually disabled by the publisher. In seconds since the epoch. + #[serde(alias="endTime")] + pub end_time: String, + /// The name of the publisher offering this direct deal. + #[serde(alias="sellerNetwork")] + pub seller_network: String, + /// Deal id. + pub id: String, + /// The minimum price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the private exchange tier of buying (below fixed price priority, run as a second price auction). + #[serde(alias="privateExchangeMinCpm")] + pub private_exchange_min_cpm: String, +} + +impl Resource for DirectDeal {} +impl ResponseResult for DirectDeal {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert pretargeting config](struct.PretargetingConfigInsertCall.html) (request|response) +/// * [patch pretargeting config](struct.PretargetingConfigPatchCall.html) (request|response) +/// * [get pretargeting config](struct.PretargetingConfigGetCall.html) (response) +/// * [update pretargeting config](struct.PretargetingConfigUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PretargetingConfig { + /// The kind of the resource, i.e. "adexchangebuyer#pretargetingConfig". + pub kind: Option, + /// Requests containing any of these vertical ids will match. + pub verticals: Option>, + /// Requests matching any of these platforms will match. Possible values are PRETARGETING_PLATFORM_MOBILE, PRETARGETING_PLATFORM_DESKTOP, and PRETARGETING_PLATFORM_TABLET. + pub platforms: Option>, + /// List must contain exactly one of PRETARGETING_CREATIVE_TYPE_HTML or PRETARGETING_CREATIVE_TYPE_VIDEO. + #[serde(alias="creativeType")] + pub creative_type: Option>, + /// Requests containing any of these geo criteria ids will match. + #[serde(alias="geoCriteriaIds")] + pub geo_criteria_ids: Option>, + /// Requests containing any of these mobile operating system version ids will match. Values are from mobile-os.csv in the downloadable files section. + #[serde(alias="mobileOperatingSystemVersions")] + pub mobile_operating_system_versions: Option>, + /// The config id; generated automatically. Leave this field blank for insert requests. + #[serde(alias="configId")] + pub config_id: Option, + /// Requests containing any of these users list ids will not match. + #[serde(alias="excludedUserLists")] + pub excluded_user_lists: Option>, + /// Whether this config is active. Required for all requests. + #[serde(alias="isActive")] + pub is_active: Option, + /// The name of the config. Must be unique. Required for all requests. + #[serde(alias="configName")] + pub config_name: Option, + /// Requests containing any of these vertical ids will not match. Values are from the publisher-verticals.txt file in the downloadable files section. + #[serde(alias="excludedVerticals")] + pub excluded_verticals: Option>, + /// Requests which allow one of these (width, height) pairs will match. All pairs must be supported ad dimensions. + pub dimensions: Option>, + /// Requests containing any of these geo criteria ids will not match. + #[serde(alias="excludedGeoCriteriaIds")] + pub excluded_geo_criteria_ids: Option>, + /// Creative attributes should be declared here if all creatives corresponding to this pretargeting configuration have that creative attribute. Values are from pretargetable-creative-attributes.txt in the downloadable files section. + #[serde(alias="supportedCreativeAttributes")] + pub supported_creative_attributes: Option>, + /// Requests with any of these content labels will not match. Values are from content-labels.txt in the downloadable files section. + #[serde(alias="excludedContentLabels")] + pub excluded_content_labels: Option>, + /// Requests that allow any of these vendor ids will match. Values are from vendors.txt in the downloadable files section. + #[serde(alias="vendorTypes")] + pub vendor_types: Option>, + /// Request containing any of these language codes will match. + pub languages: Option>, + /// Requests containing any of these user list ids will match. + #[serde(alias="userLists")] + pub user_lists: Option>, + /// Requests containing any of these mobile device ids will match. Values are from mobile-devices.csv in the downloadable files section. + #[serde(alias="mobileDevices")] + pub mobile_devices: Option>, + /// The id for billing purposes, provided for reference. Leave this field blank for insert requests; the id will be generated automatically. + #[serde(alias="billingId")] + pub billing_id: Option, + /// Requests containing any of these mobile carrier ids will match. Values are from mobile-carriers.csv in the downloadable files section. + #[serde(alias="mobileCarriers")] + pub mobile_carriers: Option>, + /// Requests containing any of these placements will not match. + #[serde(alias="excludedPlacements")] + pub excluded_placements: Option>, + /// Requests containing any of these placements will match. + pub placements: Option>, +} + +impl RequestValue for PretargetingConfig {} +impl ResponseResult for PretargetingConfig {} + + +/// Your bidder locations that have distinct URLs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountBidderLocation { + /// The URL to which the Ad Exchange will send bid requests. + pub url: String, + /// The geographical region the Ad Exchange should send requests from. Only used by some quota systems, but always setting the value is recommended. Allowed values: + /// - ASIA + /// - EUROPE + /// - US_EAST + /// - US_WEST + pub region: String, + /// The maximum queries per second the Ad Exchange will send. + #[serde(alias="maximumQps")] + pub maximum_qps: i32, +} + +impl NestedType for AccountBidderLocation {} +impl Part for AccountBidderLocation {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *billingInfo* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.billing_info(); +/// # } +/// ``` +pub struct BillingInfoMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BillingInfoMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BillingInfoMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the billing information for one account specified by account ID. + pub fn get(&self, account_id: i32) -> BillingInfoGetCall<'a, C, NC, A> { + BillingInfoGetCall { + hub: self.hub, + _account_id: account_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of billing information for all accounts of the authenticated user. + pub fn list(&self) -> BillingInfoListCall<'a, C, NC, A> { + BillingInfoListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *directDeal* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.direct_deals(); +/// # } +/// ``` +pub struct DirectDealMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DirectDealMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectDealMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the authenticated user's list of direct deals. + pub fn list(&self) -> DirectDealListCall<'a, C, NC, A> { + DirectDealListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one direct deal by ID. + pub fn get(&self, id: &str) -> DirectDealGetCall<'a, C, NC, A> { + DirectDealGetCall { + hub: self.hub, + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *budget* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.budget(); +/// # } +/// ``` +pub struct BudgetMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BudgetMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BudgetMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates the budget amount for the budget of the adgroup specified by the accountId and billingId, with the budget amount in the request. This method supports patch semantics. + pub fn patch(&self, request: &Budget, account_id: &str, billing_id: &str) -> BudgetPatchCall<'a, C, NC, A> { + BudgetPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _billing_id: billing_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the budget amount for the budget of the adgroup specified by the accountId and billingId, with the budget amount in the request. + pub fn update(&self, request: &Budget, account_id: &str, billing_id: &str) -> BudgetUpdateCall<'a, C, NC, A> { + BudgetUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _billing_id: billing_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the budget information for the adgroup specified by the accountId and billingId. + pub fn get(&self, account_id: &str, billing_id: &str) -> BudgetGetCall<'a, C, NC, A> { + BudgetGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _billing_id: billing_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creative* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.creatives(); +/// # } +/// ``` +pub struct CreativeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Submit a new creative. + pub fn insert(&self, request: &Creative) -> CreativeInsertCall<'a, C, NC, A> { + CreativeInsertCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission. + pub fn list(&self) -> CreativeListCall<'a, C, NC, A> { + CreativeListCall { + hub: self.hub, + _status_filter: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _buyer_creative_id: Default::default(), + _account_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the status for a single creative. A creative will be available 30-40 minutes after submission. + pub fn get(&self, account_id: i32, buyer_creative_id: &str) -> CreativeGetCall<'a, C, NC, A> { + CreativeGetCall { + hub: self.hub, + _account_id: account_id, + _buyer_creative_id: buyer_creative_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account. + pub fn update(&self, request: &Account, id: i32) -> AccountUpdateCall<'a, C, NC, A> { + AccountUpdateCall { + hub: self.hub, + _request: request.clone(), + _id: id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account. This method supports patch semantics. + pub fn patch(&self, request: &Account, id: i32) -> AccountPatchCall<'a, C, NC, A> { + AccountPatchCall { + hub: self.hub, + _request: request.clone(), + _id: id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the authenticated user's list of accounts. + pub fn list(&self) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one account by ID. + pub fn get(&self, id: i32) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _id: id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *performanceReport* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.performance_report(); +/// # } +/// ``` +pub struct PerformanceReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PerformanceReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PerformanceReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the authenticated user's list of performance metrics. + pub fn list(&self, account_id: &str, end_date_time: &str, start_date_time: &str) -> PerformanceReportListCall<'a, C, NC, A> { + PerformanceReportListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _end_date_time: end_date_time.to_string(), + _start_date_time: start_date_time.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *pretargetingConfig* resources. +/// It is not used directly, but through the `AdExchangeBuyer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.pretargeting_config(); +/// # } +/// ``` +pub struct PretargetingConfigMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PretargetingConfigMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing pretargeting config. + pub fn delete(&self, account_id: &str, config_id: &str) -> PretargetingConfigDeleteCall<'a, C, NC, A> { + PretargetingConfigDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _config_id: config_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing pretargeting config. This method supports patch semantics. + pub fn patch(&self, request: &PretargetingConfig, account_id: &str, config_id: &str) -> PretargetingConfigPatchCall<'a, C, NC, A> { + PretargetingConfigPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _config_id: config_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific pretargeting configuration + pub fn get(&self, account_id: &str, config_id: &str) -> PretargetingConfigGetCall<'a, C, NC, A> { + PretargetingConfigGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _config_id: config_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new pretargeting configuration. + pub fn insert(&self, request: &PretargetingConfig, account_id: &str) -> PretargetingConfigInsertCall<'a, C, NC, A> { + PretargetingConfigInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of the authenticated user's pretargeting configurations. + pub fn list(&self, account_id: &str) -> PretargetingConfigListCall<'a, C, NC, A> { + PretargetingConfigListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing pretargeting config. + pub fn update(&self, request: &PretargetingConfig, account_id: &str, config_id: &str) -> PretargetingConfigUpdateCall<'a, C, NC, A> { + PretargetingConfigUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _config_id: config_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns the billing information for one account specified by account ID. +/// +/// A builder for the *get* method supported by a *billingInfo* resource. +/// It is not used directly, but through a `BillingInfoMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.billing_info().get(-63) +/// .doit(); +/// # } +/// ``` +pub struct BillingInfoGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BillingInfoGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BillingInfoGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BillingInfo)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.billingInfo.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/billinginfo/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id. + pub fn account_id(mut self, new_value: i32) -> BillingInfoGetCall<'a, C, NC, A> { + self._account_id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingInfoGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BillingInfoGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BillingInfoGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of billing information for all accounts of the authenticated user. +/// +/// A builder for the *list* method supported by a *billingInfo* resource. +/// It is not used directly, but through a `BillingInfoMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.billing_info().list() +/// .doit(); +/// # } +/// ``` +pub struct BillingInfoListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BillingInfoListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BillingInfoListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BillingInfoList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.billingInfo.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/billinginfo".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingInfoListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BillingInfoListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BillingInfoListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the authenticated user's list of direct deals. +/// +/// A builder for the *list* method supported by a *directDeal* resource. +/// It is not used directly, but through a `DirectDealMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.direct_deals().list() +/// .doit(); +/// # } +/// ``` +pub struct DirectDealListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectDealListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectDealListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectDealsList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.directDeals.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/directdeals".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectDealListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectDealListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectDealListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one direct deal by ID. +/// +/// A builder for the *get* method supported by a *directDeal* resource. +/// It is not used directly, but through a `DirectDealMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.direct_deals().get("id") +/// .doit(); +/// # } +/// ``` +pub struct DirectDealGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectDealGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectDealGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectDeal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.directDeals.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/directdeals/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The direct deal id + pub fn id(mut self, new_value: &str) -> DirectDealGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectDealGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectDealGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectDealGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the budget amount for the budget of the adgroup specified by the accountId and billingId, with the budget amount in the request. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *budget* resource. +/// It is not used directly, but through a `BudgetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::Budget; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Budget = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.budget().patch(&req, "accountId", "billingId") +/// .doit(); +/// # } +/// ``` +pub struct BudgetPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Budget, + _account_id: String, + _billing_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BudgetPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BudgetPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Budget)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.budget.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("billingId", self._billing_id.to_string())); + for &field in ["alt", "accountId", "billingId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{billingId}", "billingId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "billingId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Budget) -> BudgetPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id associated with the budget being updated. + pub fn account_id(mut self, new_value: &str) -> BudgetPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *billing id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The billing id associated with the budget being updated. + pub fn billing_id(mut self, new_value: &str) -> BudgetPatchCall<'a, C, NC, A> { + self._billing_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BudgetPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BudgetPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the budget amount for the budget of the adgroup specified by the accountId and billingId, with the budget amount in the request. +/// +/// A builder for the *update* method supported by a *budget* resource. +/// It is not used directly, but through a `BudgetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::Budget; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Budget = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.budget().update(&req, "accountId", "billingId") +/// .doit(); +/// # } +/// ``` +pub struct BudgetUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Budget, + _account_id: String, + _billing_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BudgetUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BudgetUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Budget)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.budget.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("billingId", self._billing_id.to_string())); + for &field in ["alt", "accountId", "billingId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{billingId}", "billingId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "billingId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Budget) -> BudgetUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id associated with the budget being updated. + pub fn account_id(mut self, new_value: &str) -> BudgetUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *billing id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The billing id associated with the budget being updated. + pub fn billing_id(mut self, new_value: &str) -> BudgetUpdateCall<'a, C, NC, A> { + self._billing_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BudgetUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BudgetUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the budget information for the adgroup specified by the accountId and billingId. +/// +/// A builder for the *get* method supported by a *budget* resource. +/// It is not used directly, but through a `BudgetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.budget().get("accountId", "billingId") +/// .doit(); +/// # } +/// ``` +pub struct BudgetGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _billing_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BudgetGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BudgetGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Budget)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.budget.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("billingId", self._billing_id.to_string())); + for &field in ["alt", "accountId", "billingId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{billingId}", "billingId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "billingId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to get the budget information for. + pub fn account_id(mut self, new_value: &str) -> BudgetGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *billing id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The billing id to get the budget information for. + pub fn billing_id(mut self, new_value: &str) -> BudgetGetCall<'a, C, NC, A> { + self._billing_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BudgetGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BudgetGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Submit a new creative. +/// +/// A builder for the *insert* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Creative = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().insert(&req) +/// .doit(); +/// # } +/// ``` +pub struct CreativeInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Creative, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.creatives.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Creative) -> CreativeInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission. +/// +/// A builder for the *list* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().list() +/// .status_filter("nonumy") +/// .page_token("dolores") +/// .max_results(40) +/// .add_buyer_creative_id("sadipscing") +/// .add_account_id(-31) +/// .doit(); +/// # } +/// ``` +pub struct CreativeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _status_filter: Option, + _page_token: Option, + _max_results: Option, + _buyer_creative_id: Vec, + _account_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativesList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.creatives.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + if let Some(value) = self._status_filter { + params.push(("statusFilter", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._buyer_creative_id.len() > 0 { + let mut s = String::new(); + for f in self._buyer_creative_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("buyerCreativeId", s)); + } + if self._account_id.len() > 0 { + let mut s = String::new(); + for f in self._account_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("accountId", s)); + } + for &field in ["alt", "statusFilter", "pageToken", "maxResults", "buyerCreativeId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *status filter* query property to the given value. + /// + /// + /// When specified, only creatives having the given status are returned. + pub fn status_filter(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._status_filter = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. Optional. + pub fn page_token(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. If not set, the default is 100. Optional. + pub fn max_results(mut self, new_value: u32) -> CreativeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *buyer creative id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// When specified, only creatives for the given buyer creative ids are returned. + pub fn add_buyer_creative_id(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._buyer_creative_id.push(new_value.to_string()); + self + } + /// Append the given value to the *account id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// When specified, only creatives for the given account ids are returned. + pub fn add_account_id(mut self, new_value: i32) -> CreativeListCall<'a, C, NC, A> { + self._account_id.push(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the status for a single creative. A creative will be available 30-40 minutes after submission. +/// +/// A builder for the *get* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().get(-66, "buyerCreativeId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: i32, + _buyer_creative_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.creatives.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("buyerCreativeId", self._buyer_creative_id.to_string())); + for &field in ["alt", "accountId", "buyerCreativeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/creatives/{accountId}/{buyerCreativeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{buyerCreativeId}", "buyerCreativeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "buyerCreativeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The id for the account that will serve this creative. + pub fn account_id(mut self, new_value: i32) -> CreativeGetCall<'a, C, NC, A> { + self._account_id = new_value; + self + } + /// Sets the *buyer creative id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The buyer-specific id for this creative. + pub fn buyer_creative_id(mut self, new_value: &str) -> CreativeGetCall<'a, C, NC, A> { + self._buyer_creative_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account. +/// +/// A builder for the *update* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().update(&req, -21) +/// .doit(); +/// # } +/// ``` +pub struct AccountUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Account, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.accounts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id + pub fn id(mut self, new_value: i32) -> AccountUpdateCall<'a, C, NC, A> { + self._id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().patch(&req, -21) +/// .doit(); +/// # } +/// ``` +pub struct AccountPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Account, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.accounts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id + pub fn id(mut self, new_value: i32) -> AccountPatchCall<'a, C, NC, A> { + self._id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the authenticated user's list of accounts. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list() +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountsList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one account by ID. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get(-34) +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id + pub fn id(mut self, new_value: i32) -> AccountGetCall<'a, C, NC, A> { + self._id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the authenticated user's list of performance metrics. +/// +/// A builder for the *list* method supported by a *performanceReport* resource. +/// It is not used directly, but through a `PerformanceReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.performance_report().list("accountId", "endDateTime", "startDateTime") +/// .page_token("Lorem") +/// .max_results(80) +/// .doit(); +/// # } +/// ``` +pub struct PerformanceReportListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _end_date_time: String, + _start_date_time: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PerformanceReportListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PerformanceReportListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PerformanceReportList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.performanceReport.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("endDateTime", self._end_date_time.to_string())); + params.push(("startDateTime", self._start_date_time.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "endDateTime", "startDateTime", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/performancereport".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to get the reports. + pub fn account_id(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *end date time* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The end time of the report in ISO 8601 timestamp format using UTC. + pub fn end_date_time(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, NC, A> { + self._end_date_time = new_value.to_string(); + self + } + /// Sets the *start date time* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The start time of the report in ISO 8601 timestamp format using UTC. + pub fn start_date_time(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, NC, A> { + self._start_date_time = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through performance reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. Optional. + pub fn page_token(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. If not set, the default is 100. Optional. + pub fn max_results(mut self, new_value: u32) -> PerformanceReportListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PerformanceReportListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PerformanceReportListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PerformanceReportListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing pretargeting config. +/// +/// A builder for the *delete* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().delete("accountId", "configId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _config_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("configId", self._config_id.to_string())); + for &field in ["accountId", "configId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{configId}", "configId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "configId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to delete the pretargeting config for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *config id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The specific id of the configuration to delete. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigDeleteCall<'a, C, NC, A> { + self._config_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing pretargeting config. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PretargetingConfig = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().patch(&req, "accountId", "configId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: PretargetingConfig, + _account_id: String, + _config_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PretargetingConfig)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("configId", self._config_id.to_string())); + for &field in ["alt", "accountId", "configId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{configId}", "configId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "configId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PretargetingConfig) -> PretargetingConfigPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to update the pretargeting config for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *config id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The specific id of the configuration to update. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigPatchCall<'a, C, NC, A> { + self._config_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific pretargeting configuration +/// +/// A builder for the *get* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().get("accountId", "configId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _config_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PretargetingConfig)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("configId", self._config_id.to_string())); + for &field in ["alt", "accountId", "configId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{configId}", "configId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "configId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to get the pretargeting config for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *config id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The specific id of the configuration to retrieve. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigGetCall<'a, C, NC, A> { + self._config_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new pretargeting configuration. +/// +/// A builder for the *insert* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PretargetingConfig = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().insert(&req, "accountId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: PretargetingConfig, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PretargetingConfig)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PretargetingConfig) -> PretargetingConfigInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to insert the pretargeting config for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of the authenticated user's pretargeting configurations. +/// +/// A builder for the *list* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().list("accountId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PretargetingConfigList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to get the pretargeting configs for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing pretargeting config. +/// +/// A builder for the *update* method supported by a *pretargetingConfig* resource. +/// It is not used directly, but through a `PretargetingConfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangebuyer1d3" as adexchangebuyer1d3; +/// use adexchangebuyer1d3::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d3::AdExchangeBuyer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeBuyer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PretargetingConfig = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pretargeting_config().update(&req, "accountId", "configId") +/// .doit(); +/// # } +/// ``` +pub struct PretargetingConfigUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: PretargetingConfig, + _account_id: String, + _config_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PretargetingConfigUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PretargetingConfigUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PretargetingConfig)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangebuyer.pretargetingConfig.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("configId", self._config_id.to_string())); + for &field in ["alt", "accountId", "configId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.3/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{configId}", "configId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "configId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PretargetingConfig) -> PretargetingConfigUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The account id to update the pretargeting config for. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *config id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The specific id of the configuration to update. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigUpdateCall<'a, C, NC, A> { + self._config_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PretargetingConfigUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PretargetingConfigUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/adexchangeseller2/Cargo.toml b/gen/adexchangeseller2/Cargo.toml new file mode 100644 index 0000000000..c81088632b --- /dev/null +++ b/gen/adexchangeseller2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adexchangeseller2" +version = "0.1.0+20150313" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Ad Exchange Seller (protocol v2.0)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangeseller2" +homepage = "https://developers.google.com/ad-exchange/seller-rest/" +documentation = "http://byron.github.io/google-apis-rs/google-adexchangeseller2" +license = "MIT" +keywords = ["adexchangeseller", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/adexchangeseller2/LICENSE.md b/gen/adexchangeseller2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adexchangeseller2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/adexchangeseller2/README.md b/gen/adexchangeseller2/README.md new file mode 100644 index 0000000000..f616ef7390 --- /dev/null +++ b/gen/adexchangeseller2/README.md @@ -0,0 +1,187 @@ + +The `google-adexchangeseller2` library allows access to all features of the *Google Ad Exchange Seller* service. + +This documentation was generated from *Ad Exchange Seller* crate version *0.1.0+20150313*, where *20150313* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Ad Exchange Seller* *v2* API can be found at the +[official documentation site](https://developers.google.com/ad-exchange/seller-rest/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AdExchangeSeller.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.Account.html) + * [*adclients list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountAdclientListCall.html), [*alerts list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountAlertListCall.html), [*customchannels get*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountCustomchannelGetCall.html), [*customchannels list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountCustomchannelListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountListCall.html), [*metadata dimensions list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountMetadataDimensionListCall.html), [*metadata metrics list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountMetadataMetricListCall.html), [*preferreddeals get*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountPreferreddealGetCall.html), [*preferreddeals list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountPreferreddealListCall.html), [*reports generate*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountReportGenerateCall.html), [*reports saved generate*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountReportSavedGenerateCall.html), [*reports saved list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountReportSavedListCall.html) and [*urlchannels list*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountUrlchannelListCall.html) + + +Download supported by ... + +* [*reports generate accounts*](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AccountReportGenerateCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-adexchangeseller2/struct.AdExchangeSeller.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.accounts().reports_saved_generate(...).doit() +let r = hub.accounts().metadata_metrics_list(...).doit() +let r = hub.accounts().reports_generate(...).doit() +let r = hub.accounts().urlchannels_list(...).doit() +let r = hub.accounts().reports_saved_list(...).doit() +let r = hub.accounts().preferreddeals_get(...).doit() +let r = hub.accounts().adclients_list(...).doit() +let r = hub.accounts().metadata_dimensions_list(...).doit() +let r = hub.accounts().customchannels_get(...).doit() +let r = hub.accounts().customchannels_list(...).doit() +let r = hub.accounts().list(...).doit() +let r = hub.accounts().alerts_list(...).doit() +let r = hub.accounts().preferreddeals_list(...).doit() +let r = hub.accounts().get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-adexchangeseller2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-adexchangeseller2" as adexchangeseller2; +use adexchangeseller2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use adexchangeseller2::AdExchangeSeller; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") + .start_index(59) + .add_sort("et") + .add_metric("dolores") + .max_results(38) + .locale("accusam") + .add_filter("takimata") + .add_dimension("justo") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-adexchangeseller2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-adexchangeseller2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-adexchangeseller2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-adexchangeseller2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **adexchangeseller2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/adexchangeseller2/src/cmn.rs b/gen/adexchangeseller2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/adexchangeseller2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/adexchangeseller2/src/lib.rs b/gen/adexchangeseller2/src/lib.rs new file mode 100644 index 0000000000..197d8fe75e --- /dev/null +++ b/gen/adexchangeseller2/src/lib.rs @@ -0,0 +1,4703 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Ad Exchange Seller* crate version *0.1.0+20150313*, where *20150313* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Ad Exchange Seller* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/ad-exchange/seller-rest/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangeseller2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AdExchangeSeller.html) ... +//! +//! * [accounts](struct.Account.html) +//! * [*adclients list*](struct.AccountAdclientListCall.html), [*alerts list*](struct.AccountAlertListCall.html), [*customchannels get*](struct.AccountCustomchannelGetCall.html), [*customchannels list*](struct.AccountCustomchannelListCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*metadata dimensions list*](struct.AccountMetadataDimensionListCall.html), [*metadata metrics list*](struct.AccountMetadataMetricListCall.html), [*preferreddeals get*](struct.AccountPreferreddealGetCall.html), [*preferreddeals list*](struct.AccountPreferreddealListCall.html), [*reports generate*](struct.AccountReportGenerateCall.html), [*reports saved generate*](struct.AccountReportSavedGenerateCall.html), [*reports saved list*](struct.AccountReportSavedListCall.html) and [*urlchannels list*](struct.AccountUrlchannelListCall.html) +//! +//! +//! Download supported by ... +//! +//! * [*reports generate accounts*](struct.AccountReportGenerateCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AdExchangeSeller.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.accounts().reports_saved_generate(...).doit() +//! let r = hub.accounts().metadata_metrics_list(...).doit() +//! let r = hub.accounts().reports_generate(...).doit() +//! let r = hub.accounts().urlchannels_list(...).doit() +//! let r = hub.accounts().reports_saved_list(...).doit() +//! let r = hub.accounts().preferreddeals_get(...).doit() +//! let r = hub.accounts().adclients_list(...).doit() +//! let r = hub.accounts().metadata_dimensions_list(...).doit() +//! let r = hub.accounts().customchannels_get(...).doit() +//! let r = hub.accounts().customchannels_list(...).doit() +//! let r = hub.accounts().list(...).doit() +//! let r = hub.accounts().alerts_list(...).doit() +//! let r = hub.accounts().preferreddeals_list(...).doit() +//! let r = hub.accounts().get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-adexchangeseller2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-adexchangeseller2" as adexchangeseller2; +//! use adexchangeseller2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use adexchangeseller2::AdExchangeSeller; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +//! .start_index(92) +//! .add_sort("nonumy") +//! .add_metric("dolores") +//! .max_results(40) +//! .locale("sadipscing") +//! .add_filter("aliquyam") +//! .add_dimension("ea") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your Ad Exchange data + AdexchangeSellerReadonly, + + /// View and manage your Ad Exchange data + AdexchangeSeller, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::AdexchangeSellerReadonly => "https://www.googleapis.com/auth/adexchange.seller.readonly", + Scope::AdexchangeSeller => "https://www.googleapis.com/auth/adexchange.seller", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::AdexchangeSellerReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AdExchangeSeller related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangeseller2" as adexchangeseller2; +/// use adexchangeseller2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangeseller2::AdExchangeSeller; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .start_index(67) +/// .add_sort("et") +/// .add_metric("diam") +/// .max_results(46) +/// .locale("Lorem") +/// .add_filter("et") +/// .add_dimension("duo") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AdExchangeSeller { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AdExchangeSeller {} + +impl<'a, C, NC, A> AdExchangeSeller + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AdExchangeSeller { + AdExchangeSeller { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [urlchannels list accounts](struct.AccountUrlchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlChannels { + /// Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The URL channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#urlChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for UrlChannels {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [reports saved generate accounts](struct.AccountReportSavedGenerateCall.html) (none) +/// * [metadata metrics list accounts](struct.AccountMetadataMetricListCall.html) (none) +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (none) +/// * [urlchannels list accounts](struct.AccountUrlchannelListCall.html) (none) +/// * [reports saved list accounts](struct.AccountReportSavedListCall.html) (none) +/// * [preferreddeals get accounts](struct.AccountPreferreddealGetCall.html) (none) +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (none) +/// * [metadata dimensions list accounts](struct.AccountMetadataDimensionListCall.html) (none) +/// * [customchannels get accounts](struct.AccountCustomchannelGetCall.html) (none) +/// * [customchannels list accounts](struct.AccountCustomchannelListCall.html) (none) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [alerts list accounts](struct.AccountAlertListCall.html) (none) +/// * [preferreddeals list accounts](struct.AccountPreferreddealListCall.html) (none) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Account { + /// Kind of resource this is, in this case adexchangeseller#account. + pub kind: String, + /// Unique identifier of this account. + pub id: String, + /// Name of this account. + pub name: String, +} + +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [customchannels list accounts](struct.AccountCustomchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannels { + /// Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The custom channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#customChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for CustomChannels {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [alerts list accounts](struct.AccountAlertListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Alerts { + /// The alerts returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#alerts. + pub kind: String, +} + +impl ResponseResult for Alerts {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedReport { + /// Kind of resource this is, in this case adexchangeseller#savedReport. + pub kind: String, + /// Unique identifier of this saved report. + pub id: String, + /// This saved report's name. + pub name: String, +} + +impl Part for SavedReport {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClient { + /// This ad client's product code, which corresponds to the PRODUCT_CODE report dimension. + #[serde(alias="productCode")] + pub product_code: String, + /// Kind of resource this is, in this case adexchangeseller#adClient. + pub kind: String, + /// Unique identifier of this ad client. + pub id: String, + /// Whether this ad client is opted in to ARC. + #[serde(alias="arcOptIn")] + pub arc_opt_in: bool, + /// Whether this ad client supports being reported on. + #[serde(alias="supportsReporting")] + pub supports_reporting: bool, +} + +impl Part for AdClient {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [preferreddeals list accounts](struct.AccountPreferreddealListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PreferredDeals { + /// The preferred deals returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#preferredDeals. + pub kind: String, +} + +impl ResponseResult for PreferredDeals {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportingMetadataEntry { + /// The names of the metrics which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report to be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted. + #[serde(alias="requiredMetrics")] + pub required_metrics: Vec, + /// Kind of resource this is, in this case adexchangeseller#reportingMetadataEntry. + pub kind: String, + /// The names of the metrics the dimension or metric this reporting metadata entry describes is compatible with. + #[serde(alias="compatibleMetrics")] + pub compatible_metrics: Vec, + /// For metrics this is a list of dimension IDs which the metric is compatible with, for dimensions it is a list of compatibility groups the dimension belongs to. + #[serde(alias="compatibleDimensions")] + pub compatible_dimensions: Vec, + /// Unique identifier of this reporting metadata entry, corresponding to the name of the appropriate dimension or metric. + pub id: String, + /// The names of the dimensions which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report to be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted. + #[serde(alias="requiredDimensions")] + pub required_dimensions: Vec, + /// The codes of the projects supported by the dimension or metric this reporting metadata entry describes. + #[serde(alias="supportedProducts")] + pub supported_products: Vec, +} + +impl Part for ReportingMetadataEntry {} + + +/// The targeting information of this custom channel, if activated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannelTargetingInfo { + /// The external description of the channel. + pub description: String, + /// The language of the sites ads will be displayed on. + #[serde(alias="siteLanguage")] + pub site_language: String, + /// The locations in which ads appear. (Only valid for content and mobile content ads). Acceptable values for content ads are: TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, MULTIPLE_LOCATIONS. Acceptable values for mobile content ads are: TOP, MIDDLE, BOTTOM, MULTIPLE_LOCATIONS. + pub location: String, + /// The name used to describe this channel externally. + #[serde(alias="adsAppearOn")] + pub ads_appear_on: String, +} + +impl NestedType for CustomChannelTargetingInfo {} +impl Part for CustomChannelTargetingInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [metadata dimensions list accounts](struct.AccountMetadataDimensionListCall.html) (response) +/// * [metadata metrics list accounts](struct.AccountMetadataMetricListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Metadata { + /// no description provided + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#metadata. + pub kind: String, +} + +impl ResponseResult for Metadata {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlChannel { + /// Kind of resource this is, in this case adexchangeseller#urlChannel. + pub kind: String, + /// Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// URL Pattern of this URL channel. Does not include "http://" or "https://". Example: www.example.com/home + #[serde(alias="urlPattern")] + pub url_pattern: String, +} + +impl Part for UrlChannel {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClients { + /// Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The ad clients returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#adClients. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for AdClients {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [preferreddeals get accounts](struct.AccountPreferreddealGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PreferredDeal { + /// Kind of resource this is, in this case adexchangeseller#preferredDeal. + pub kind: String, + /// The name of the buyer network this deal is for. + #[serde(alias="buyerNetworkName")] + pub buyer_network_name: String, + /// The currency code that applies to the fixed_cpm value. If not set then assumed to be USD. + #[serde(alias="currencyCode")] + pub currency_code: String, + /// The name of the advertiser this deal is for. + #[serde(alias="advertiserName")] + pub advertiser_name: String, + /// The fixed price for this preferred deal. In cpm micros of currency according to currencyCode. If set, then this preferred deal is eligible for the fixed price tier of buying (highest priority, pay exactly the configured fixed price). + #[serde(alias="fixedCpm")] + pub fixed_cpm: String, + /// Time when this deal becomes active in seconds since the epoch (GMT). If not set then this deal is active immediately upon creation. + #[serde(alias="startTime")] + pub start_time: String, + /// Time when this deal stops being active in seconds since the epoch (GMT). If not set then this deal is valid until manually disabled by the publisher. + #[serde(alias="endTime")] + pub end_time: String, + /// Unique identifier of this preferred deal. + pub id: String, +} + +impl ResponseResult for PreferredDeal {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [reports saved list accounts](struct.AccountReportSavedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedReports { + /// Continuation token used to page through saved reports. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The saved reports returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#savedReports. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for SavedReports {} + + +/// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportHeaders { + /// The currency of this column. Only present if the header type is METRIC_CURRENCY. + pub currency: String, + /// The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY. + #[serde(alias="type")] + pub type_: String, + /// The name of the header. + pub name: String, +} + +impl NestedType for ReportHeaders {} +impl Part for ReportHeaders {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Alert { + /// Unique identifier of this alert. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// Kind of resource this is, in this case adexchangeseller#alert. + pub kind: String, + /// Type of this alert. Possible values: SELF_HOLD, MIGRATED_TO_BILLING3, ADDRESS_PIN_VERIFICATION, PHONE_PIN_VERIFICATION, CORPORATE_ENTITY, GRAYLISTED_PUBLISHER, API_HOLD. + #[serde(alias="type")] + pub type_: String, + /// The localized alert message. + pub message: String, + /// Severity of this alert. Possible values: INFO, WARNING, SEVERE. + pub severity: String, +} + +impl Part for Alert {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Accounts { + /// Continuation token used to page through accounts. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The accounts returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adexchangeseller#accounts. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for Accounts {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [reports saved generate accounts](struct.AccountReportSavedGenerateCall.html) (response) +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Report { + /// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. + pub headers: Vec, + /// Kind this is, in this case adexchangeseller#report. + pub kind: String, + /// The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The dimension cells contain strings, and the metric cells contain numbers. + pub rows: Vec>, + /// The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or the report row limit. + #[serde(alias="totalMatchedRows")] + pub total_matched_rows: String, + /// Any warnings associated with generation of the report. + pub warnings: Vec, + /// The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub averages: Vec, + /// The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub totals: Vec, +} + +impl ResponseResult for Report {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [customchannels get accounts](struct.AccountCustomchannelGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannel { + /// Kind of resource this is, in this case adexchangeseller#customChannel. + pub kind: String, + /// Code of this custom channel, not necessarily unique across ad clients. + pub code: String, + /// The targeting information of this custom channel, if activated. + #[serde(alias="targetingInfo")] + pub targeting_info: CustomChannelTargetingInfo, + /// Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// Name of this custom channel. + pub name: String, +} + +impl ResponseResult for CustomChannel {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `AdExchangeSeller` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adexchangeseller2" as adexchangeseller2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangeseller2::AdExchangeSeller; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `adclients_list(...)`, `alerts_list(...)`, `customchannels_get(...)`, `customchannels_list(...)`, `get(...)`, `list(...)`, `metadata_dimensions_list(...)`, `metadata_metrics_list(...)`, `preferreddeals_get(...)`, `preferreddeals_list(...)`, `reports_generate(...)`, `reports_saved_generate(...)`, `reports_saved_list(...)` and `urlchannels_list(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Generate an Ad Exchange report based on the saved report ID sent in the query parameters. + pub fn reports_saved_generate(&self, account_id: &str, saved_report_id: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + AccountReportSavedGenerateCall { + hub: self.hub, + _account_id: account_id.to_string(), + _saved_report_id: saved_report_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the metadata for the metrics available to this AdExchange account. + pub fn metadata_metrics_list(&self, account_id: &str) -> AccountMetadataMetricListCall<'a, C, NC, A> { + AccountMetadataMetricListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an Ad Exchange report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. + pub fn reports_generate(&self, account_id: &str, start_date: &str, end_date: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + AccountReportGenerateCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _start_index: Default::default(), + _sort: Default::default(), + _metric: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _filter: Default::default(), + _dimension: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all URL channels in the specified ad client for this Ad Exchange account. + pub fn urlchannels_list(&self, account_id: &str, ad_client_id: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + AccountUrlchannelListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all saved reports in this Ad Exchange account. + pub fn reports_saved_list(&self, account_id: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + AccountReportSavedListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about the selected Ad Exchange Preferred Deal. + pub fn preferreddeals_get(&self, account_id: &str, deal_id: &str) -> AccountPreferreddealGetCall<'a, C, NC, A> { + AccountPreferreddealGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _deal_id: deal_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad clients in this Ad Exchange account. + pub fn adclients_list(&self, account_id: &str) -> AccountAdclientListCall<'a, C, NC, A> { + AccountAdclientListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the metadata for the dimensions available to this AdExchange account. + pub fn metadata_dimensions_list(&self, account_id: &str) -> AccountMetadataDimensionListCall<'a, C, NC, A> { + AccountMetadataDimensionListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get the specified custom channel from the specified ad client. + pub fn customchannels_get(&self, account_id: &str, ad_client_id: &str, custom_channel_id: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + AccountCustomchannelGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all custom channels in the specified ad client for this Ad Exchange account. + pub fn customchannels_list(&self, account_id: &str, ad_client_id: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + AccountCustomchannelListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all accounts available to this Ad Exchange account. + pub fn list(&self) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the alerts for this Ad Exchange account. + pub fn alerts_list(&self, account_id: &str) -> AccountAlertListCall<'a, C, NC, A> { + AccountAlertListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the preferred deals for this Ad Exchange account. + pub fn preferreddeals_list(&self, account_id: &str) -> AccountPreferreddealListCall<'a, C, NC, A> { + AccountPreferreddealListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about the selected Ad Exchange account. + pub fn get(&self, account_id: &str) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Generate an Ad Exchange report based on the saved report ID sent in the query parameters. +/// +/// A builder for the *reports.saved.generate* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_saved_generate("accountId", "savedReportId") +/// .start_index(-55) +/// .max_results(-75) +/// .locale("erat") +/// .doit(); +/// # } +/// ``` +pub struct AccountReportSavedGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _saved_report_id: String, + _start_index: Option, + _max_results: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportSavedGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportSavedGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.reports.saved.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("savedReportId", self._saved_report_id.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "accountId", "savedReportId", "startIndex", "maxResults", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/reports/{savedReportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{savedReportId}", "savedReportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "savedReportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account owning the saved report. + pub fn account_id(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *saved report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The saved report to retrieve. + pub fn saved_report_id(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._saved_report_id = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: i32) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: i32) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the metadata for the metrics available to this AdExchange account. +/// +/// A builder for the *metadata.metrics.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().metadata_metrics_list("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountMetadataMetricListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountMetadataMetricListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMetadataMetricListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Metadata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.metadata.metrics.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/metadata/metrics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account with visibility to the metrics. + pub fn account_id(mut self, new_value: &str) -> AccountMetadataMetricListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountMetadataMetricListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountMetadataMetricListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountMetadataMetricListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an Ad Exchange report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `Report` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *reports.generate* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .start_index(4) +/// .add_sort("no") +/// .add_metric("labore") +/// .max_results(62) +/// .locale("dolore") +/// .add_filter("invidunt") +/// .add_dimension("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct AccountReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _start_date: String, + _end_date: String, + _start_index: Option, + _sort: Vec, + _metric: Vec, + _max_results: Option, + _locale: Option, + _filter: Vec, + _dimension: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.reports.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("startDate", self._start_date.to_string())); + params.push(("endDate", self._end_date.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if self._sort.len() > 0 { + let mut s = String::new(); + for f in self._sort.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sort", s)); + } + if self._metric.len() > 0 { + let mut s = String::new(); + for f in self._metric.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("metric", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if self._dimension.len() > 0 { + let mut s = String::new(); + for f in self._dimension.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dimension", s)); + } + for &field in ["accountId", "startDate", "endDate", "startIndex", "sort", "metric", "maxResults", "locale", "filter", "dimension"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which owns the generated report. + pub fn account_id(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn start_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn end_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: u32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Append the given value to the *sort* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. + pub fn add_sort(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._sort.push(new_value.to_string()); + self + } + /// Append the given value to the *metric* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Numeric columns to include in the report. + pub fn add_metric(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._metric.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: u32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filters to be run on the report. + pub fn add_filter(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Append the given value to the *dimension* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Dimensions to base the report on. + pub fn add_dimension(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._dimension.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all URL channels in the specified ad client for this Ad Exchange account. +/// +/// A builder for the *urlchannels.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().urlchannels_list("accountId", "adClientId") +/// .page_token("sea") +/// .max_results(80) +/// .doit(); +/// # } +/// ``` +pub struct AccountUrlchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUrlchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUrlchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.urlchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/adclients/{adClientId}/urlchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list URL channels. + pub fn ad_client_id(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of URL channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUrlchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUrlchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all saved reports in this Ad Exchange account. +/// +/// A builder for the *reports.saved.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_saved_list("accountId") +/// .page_token("et") +/// .max_results(-40) +/// .doit(); +/// # } +/// ``` +pub struct AccountReportSavedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportSavedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportSavedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.reports.saved.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/reports/saved".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account owning the saved reports. + pub fn account_id(mut self, new_value: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of saved reports to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountReportSavedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportSavedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportSavedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportSavedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about the selected Ad Exchange Preferred Deal. +/// +/// A builder for the *preferreddeals.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().preferreddeals_get("accountId", "dealId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPreferreddealGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _deal_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPreferreddealGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPreferreddealGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PreferredDeal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.preferreddeals.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("dealId", self._deal_id.to_string())); + for &field in ["alt", "accountId", "dealId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/preferreddeals/{dealId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{dealId}", "dealId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "dealId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account owning the deal. + pub fn account_id(mut self, new_value: &str) -> AccountPreferreddealGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *deal id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Preferred deal to get information about. + pub fn deal_id(mut self, new_value: &str) -> AccountPreferreddealGetCall<'a, C, NC, A> { + self._deal_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPreferreddealGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPreferreddealGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPreferreddealGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad clients in this Ad Exchange account. +/// +/// A builder for the *adclients.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adclients_list("accountId") +/// .page_token("et") +/// .max_results(56) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdclientListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdclientListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdclientListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClients)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.adclients.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/adclients".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad clients to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountAdclientListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdclientListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the metadata for the dimensions available to this AdExchange account. +/// +/// A builder for the *metadata.dimensions.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().metadata_dimensions_list("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountMetadataDimensionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountMetadataDimensionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMetadataDimensionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Metadata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.metadata.dimensions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/metadata/dimensions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account with visibility to the dimensions. + pub fn account_id(mut self, new_value: &str) -> AccountMetadataDimensionListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountMetadataDimensionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountMetadataDimensionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountMetadataDimensionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get the specified custom channel from the specified ad client. +/// +/// A builder for the *customchannels.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().customchannels_get("accountId", "adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct AccountCustomchannelGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustomchannelGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustomchannelGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.customchannels.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to retrieve. + pub fn custom_channel_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all custom channels in the specified ad client for this Ad Exchange account. +/// +/// A builder for the *customchannels.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().customchannels_list("accountId", "adClientId") +/// .page_token("et") +/// .max_results(5) +/// .doit(); +/// # } +/// ``` +pub struct AccountCustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list custom channels. + pub fn ad_client_id(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all accounts available to this Ad Exchange account. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list() +/// .page_token("amet.") +/// .max_results(-27) +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Accounts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through accounts. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of accounts to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the alerts for this Ad Exchange account. +/// +/// A builder for the *alerts.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().alerts_list("accountId") +/// .locale("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct AccountAlertListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAlertListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAlertListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Alerts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.alerts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "accountId", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/alerts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account owning the alerts. + pub fn account_id(mut self, new_value: &str) -> AccountAlertListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale to use for translating alert messages. The account locale will be used if this is not supplied. The AdSense default (English) will be used if the supplied locale is invalid or unsupported. + pub fn locale(mut self, new_value: &str) -> AccountAlertListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAlertListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAlertListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAlertListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the preferred deals for this Ad Exchange account. +/// +/// A builder for the *preferreddeals.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().preferreddeals_list("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPreferreddealListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPreferreddealListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPreferreddealListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PreferredDeals)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.preferreddeals.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}/preferreddeals".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account owning the deals. + pub fn account_id(mut self, new_value: &str) -> AccountPreferreddealListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPreferreddealListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPreferreddealListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPreferreddealListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about the selected Ad Exchange account. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adexchangeseller2" as adexchangeseller2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangeseller2::AdExchangeSeller; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdExchangeSeller::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdExchangeSeller, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adexchangeseller.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adexchangeseller/v2.0/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeSellerReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to get information about. Tip: 'myaccount' is a valid ID. + pub fn account_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/admin1_directory/Cargo.toml b/gen/admin1_directory/Cargo.toml new file mode 100644 index 0000000000..8e75af634a --- /dev/null +++ b/gen/admin1_directory/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-admin1_directory" +version = "0.1.0+20150123" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with directory (protocol directory_v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/admin1_directory" +homepage = "https://developers.google.com/admin-sdk/directory/" +documentation = "http://byron.github.io/google-apis-rs/google-admin1_directory" +license = "MIT" +keywords = ["admin", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/admin1_directory/LICENSE.md b/gen/admin1_directory/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/admin1_directory/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/admin1_directory/README.md b/gen/admin1_directory/README.md new file mode 100644 index 0000000000..9b6b4fdeae --- /dev/null +++ b/gen/admin1_directory/README.md @@ -0,0 +1,227 @@ + +The `google-admin1_directory` library allows access to all features of the *Google directory* service. + +This documentation was generated from *directory* crate version *0.1.0+20150123*, where *20150123* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *directory* *v1_directory* API can be found at the +[official documentation site](https://developers.google.com/admin-sdk/directory/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Directory.html) ... + +* [asps](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Asp.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.AspDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.AspGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.AspListCall.html) +* [channels](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Channel.html) + * [*stop*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.ChannelStopCall.html) +* chromeosdevices + * [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.ChromeosdeviceGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.ChromeosdeviceListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.ChromeosdevicePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.ChromeosdeviceUpdateCall.html) +* [groups](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Group.html) + * [*aliases delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupAliaseDeleteCall.html), [*aliases insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupAliaseInsertCall.html), [*aliases list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupAliaseListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupUpdateCall.html) +* [members](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Member.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MemberUpdateCall.html) +* mobiledevices + * [*action*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MobiledeviceActionCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MobiledeviceDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MobiledeviceGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.MobiledeviceListCall.html) +* [notifications](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Notification.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.NotificationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.NotificationGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.NotificationListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.NotificationPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.NotificationUpdateCall.html) +* orgunits + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.OrgunitUpdateCall.html) +* [schemas](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Schema.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.SchemaUpdateCall.html) +* [tokens](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Token.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.TokenDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.TokenGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.TokenListCall.html) +* [users](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.User.html) + * [*aliases delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseDeleteCall.html), [*aliases insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseInsertCall.html), [*aliases list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseListCall.html), [*aliases watch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseWatchCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserListCall.html), [*make admin*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserMakeAdminCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserPatchCall.html), [*photos delete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserPhotoDeleteCall.html), [*photos get*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserPhotoGetCall.html), [*photos patch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserPhotoPatchCall.html), [*photos update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserPhotoUpdateCall.html), [*undelete*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserUndeleteCall.html), [*update*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserUpdateCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserWatchCall.html) +* [verification codes](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.VerificationCode.html) + * [*generate*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.VerificationCodeGenerateCall.html), [*invalidate*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.VerificationCodeInvalidateCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.VerificationCodeListCall.html) + + +Subscription supported by ... + +* [*list users*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserListCall.html) +* [*aliases list users*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseListCall.html) +* [*watch users*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserWatchCall.html) +* [*aliases watch users*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.UserAliaseWatchCall.html) +* [*aliases list groups*](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.GroupAliaseListCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-admin1_directory/struct.Directory.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.users().photos_patch(...).doit() +let r = hub.users().aliases_delete(...).doit() +let r = hub.users().undelete(...).doit() +let r = hub.users().photos_get(...).doit() +let r = hub.users().update(...).doit() +let r = hub.users().aliases_watch(...).doit() +let r = hub.users().insert(...).doit() +let r = hub.users().photos_delete(...).doit() +let r = hub.users().patch(...).doit() +let r = hub.users().photos_update(...).doit() +let r = hub.users().watch(...).doit() +let r = hub.users().get(...).doit() +let r = hub.users().aliases_insert(...).doit() +let r = hub.users().make_admin(...).doit() +let r = hub.users().aliases_list(...).doit() +let r = hub.users().list(...).doit() +let r = hub.users().delete(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-admin1_directory = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-admin1_directory" as admin1_directory; +use admin1_directory::Channel; +use admin1_directory::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use admin1_directory::Directory; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Directory::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Channel = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.users().watch(&req) + .view_type("eirmod") + .sort_order("sit") + .show_deleted("Stet") + .query("sed") + .projection("et") + .page_token("dolores") + .order_by("kasd") + .max_results(-22) + .event("takimata") + .domain("justo") + .customer("amet.") + .custom_field_mask("erat") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-admin1_directory/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-admin1_directory/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-admin1_directory/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-admin1_directory/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **admin1_directory** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/admin1_directory/src/cmn.rs b/gen/admin1_directory/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/admin1_directory/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/admin1_directory/src/lib.rs b/gen/admin1_directory/src/lib.rs new file mode 100644 index 0000000000..e4a00bac72 --- /dev/null +++ b/gen/admin1_directory/src/lib.rs @@ -0,0 +1,20120 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *directory* crate version *0.1.0+20150123*, where *20150123* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *directory* *v1_directory* API can be found at the +//! [official documentation site](https://developers.google.com/admin-sdk/directory/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/admin1_directory). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Directory.html) ... +//! +//! * [asps](struct.Asp.html) +//! * [*delete*](struct.AspDeleteCall.html), [*get*](struct.AspGetCall.html) and [*list*](struct.AspListCall.html) +//! * [channels](struct.Channel.html) +//! * [*stop*](struct.ChannelStopCall.html) +//! * chromeosdevices +//! * [*get*](struct.ChromeosdeviceGetCall.html), [*list*](struct.ChromeosdeviceListCall.html), [*patch*](struct.ChromeosdevicePatchCall.html) and [*update*](struct.ChromeosdeviceUpdateCall.html) +//! * [groups](struct.Group.html) +//! * [*aliases delete*](struct.GroupAliaseDeleteCall.html), [*aliases insert*](struct.GroupAliaseInsertCall.html), [*aliases list*](struct.GroupAliaseListCall.html), [*delete*](struct.GroupDeleteCall.html), [*get*](struct.GroupGetCall.html), [*insert*](struct.GroupInsertCall.html), [*list*](struct.GroupListCall.html), [*patch*](struct.GroupPatchCall.html) and [*update*](struct.GroupUpdateCall.html) +//! * [members](struct.Member.html) +//! * [*delete*](struct.MemberDeleteCall.html), [*get*](struct.MemberGetCall.html), [*insert*](struct.MemberInsertCall.html), [*list*](struct.MemberListCall.html), [*patch*](struct.MemberPatchCall.html) and [*update*](struct.MemberUpdateCall.html) +//! * mobiledevices +//! * [*action*](struct.MobiledeviceActionCall.html), [*delete*](struct.MobiledeviceDeleteCall.html), [*get*](struct.MobiledeviceGetCall.html) and [*list*](struct.MobiledeviceListCall.html) +//! * [notifications](struct.Notification.html) +//! * [*delete*](struct.NotificationDeleteCall.html), [*get*](struct.NotificationGetCall.html), [*list*](struct.NotificationListCall.html), [*patch*](struct.NotificationPatchCall.html) and [*update*](struct.NotificationUpdateCall.html) +//! * orgunits +//! * [*delete*](struct.OrgunitDeleteCall.html), [*get*](struct.OrgunitGetCall.html), [*insert*](struct.OrgunitInsertCall.html), [*list*](struct.OrgunitListCall.html), [*patch*](struct.OrgunitPatchCall.html) and [*update*](struct.OrgunitUpdateCall.html) +//! * [schemas](struct.Schema.html) +//! * [*delete*](struct.SchemaDeleteCall.html), [*get*](struct.SchemaGetCall.html), [*insert*](struct.SchemaInsertCall.html), [*list*](struct.SchemaListCall.html), [*patch*](struct.SchemaPatchCall.html) and [*update*](struct.SchemaUpdateCall.html) +//! * [tokens](struct.Token.html) +//! * [*delete*](struct.TokenDeleteCall.html), [*get*](struct.TokenGetCall.html) and [*list*](struct.TokenListCall.html) +//! * [users](struct.User.html) +//! * [*aliases delete*](struct.UserAliaseDeleteCall.html), [*aliases insert*](struct.UserAliaseInsertCall.html), [*aliases list*](struct.UserAliaseListCall.html), [*aliases watch*](struct.UserAliaseWatchCall.html), [*delete*](struct.UserDeleteCall.html), [*get*](struct.UserGetCall.html), [*insert*](struct.UserInsertCall.html), [*list*](struct.UserListCall.html), [*make admin*](struct.UserMakeAdminCall.html), [*patch*](struct.UserPatchCall.html), [*photos delete*](struct.UserPhotoDeleteCall.html), [*photos get*](struct.UserPhotoGetCall.html), [*photos patch*](struct.UserPhotoPatchCall.html), [*photos update*](struct.UserPhotoUpdateCall.html), [*undelete*](struct.UserUndeleteCall.html), [*update*](struct.UserUpdateCall.html) and [*watch*](struct.UserWatchCall.html) +//! * [verification codes](struct.VerificationCode.html) +//! * [*generate*](struct.VerificationCodeGenerateCall.html), [*invalidate*](struct.VerificationCodeInvalidateCall.html) and [*list*](struct.VerificationCodeListCall.html) +//! +//! +//! Subscription supported by ... +//! +//! * [*list users*](struct.UserListCall.html) +//! * [*aliases list users*](struct.UserAliaseListCall.html) +//! * [*watch users*](struct.UserWatchCall.html) +//! * [*aliases watch users*](struct.UserAliaseWatchCall.html) +//! * [*aliases list groups*](struct.GroupAliaseListCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Directory.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.users().photos_patch(...).doit() +//! let r = hub.users().aliases_delete(...).doit() +//! let r = hub.users().undelete(...).doit() +//! let r = hub.users().photos_get(...).doit() +//! let r = hub.users().update(...).doit() +//! let r = hub.users().aliases_watch(...).doit() +//! let r = hub.users().insert(...).doit() +//! let r = hub.users().photos_delete(...).doit() +//! let r = hub.users().patch(...).doit() +//! let r = hub.users().photos_update(...).doit() +//! let r = hub.users().watch(...).doit() +//! let r = hub.users().get(...).doit() +//! let r = hub.users().aliases_insert(...).doit() +//! let r = hub.users().make_admin(...).doit() +//! let r = hub.users().aliases_list(...).doit() +//! let r = hub.users().list(...).doit() +//! let r = hub.users().delete(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-admin1_directory = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-admin1_directory" as admin1_directory; +//! use admin1_directory::Channel; +//! use admin1_directory::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use admin1_directory::Directory; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Directory::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Channel = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.users().watch(&req) +//! .view_type("labore") +//! .sort_order("sea") +//! .show_deleted("nonumy") +//! .query("dolores") +//! .projection("gubergren") +//! .page_token("sadipscing") +//! .order_by("aliquyam") +//! .max_results(-66) +//! .event("no") +//! .domain("justo") +//! .customer("justo") +//! .custom_field_mask("et") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage user aliases on your domain + DirectoryUserAlia, + + /// View your mobile devices' metadata + DirectoryDeviceMobileReadonly, + + /// View and manage notifications received on your domain + DirectoryNotification, + + /// View groups on your domain + DirectoryGroupReadonly, + + /// View and manage the provisioning of user schemas on your domain + DirectoryUserschema, + + /// View your Chrome OS devices' metadata + DirectoryDeviceChromeoReadonly, + + /// View group subscriptions on your domain + DirectoryGroupMemberReadonly, + + /// Manage data access permissions for users on your domain + DirectoryUserSecurity, + + /// View organization units on your domain + DirectoryOrgunitReadonly, + + /// View and manage group subscriptions on your domain + DirectoryGroupMember, + + /// View and manage your mobile devices' metadata + DirectoryDeviceMobile, + + /// View and manage the provisioning of users on your domain + DirectoryUser, + + /// Manage your mobile devices by performing administrative tasks + DirectoryDeviceMobileAction, + + /// View users on your domain + DirectoryUserReadonly, + + /// View and manage your Chrome OS devices' metadata + DirectoryDeviceChromeo, + + /// View user aliases on your domain + DirectoryUserAliaReadonly, + + /// View and manage the provisioning of groups on your domain + DirectoryGroup, + + /// View user schemas on your domain + DirectoryUserschemaReadonly, + + /// View and manage organization units on your domain + DirectoryOrgunit, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::DirectoryUserAlia => "https://www.googleapis.com/auth/admin.directory.user.alias", + Scope::DirectoryDeviceMobileReadonly => "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly", + Scope::DirectoryNotification => "https://www.googleapis.com/auth/admin.directory.notifications", + Scope::DirectoryGroupReadonly => "https://www.googleapis.com/auth/admin.directory.group.readonly", + Scope::DirectoryUserschema => "https://www.googleapis.com/auth/admin.directory.userschema", + Scope::DirectoryDeviceChromeoReadonly => "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly", + Scope::DirectoryGroupMemberReadonly => "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + Scope::DirectoryUserSecurity => "https://www.googleapis.com/auth/admin.directory.user.security", + Scope::DirectoryOrgunitReadonly => "https://www.googleapis.com/auth/admin.directory.orgunit.readonly", + Scope::DirectoryGroupMember => "https://www.googleapis.com/auth/admin.directory.group.member", + Scope::DirectoryDeviceMobile => "https://www.googleapis.com/auth/admin.directory.device.mobile", + Scope::DirectoryUser => "https://www.googleapis.com/auth/admin.directory.user", + Scope::DirectoryDeviceMobileAction => "https://www.googleapis.com/auth/admin.directory.device.mobile.action", + Scope::DirectoryUserReadonly => "https://www.googleapis.com/auth/admin.directory.user.readonly", + Scope::DirectoryDeviceChromeo => "https://www.googleapis.com/auth/admin.directory.device.chromeos", + Scope::DirectoryUserAliaReadonly => "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", + Scope::DirectoryGroup => "https://www.googleapis.com/auth/admin.directory.group", + Scope::DirectoryUserschemaReadonly => "https://www.googleapis.com/auth/admin.directory.userschema.readonly", + Scope::DirectoryOrgunit => "https://www.googleapis.com/auth/admin.directory.orgunit", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::DirectoryDeviceMobileReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Directory related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Channel; +/// use admin1_directory::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().watch(&req) +/// .view_type("et") +/// .sort_order("diam") +/// .show_deleted("ipsum") +/// .query("Lorem") +/// .projection("et") +/// .page_token("duo") +/// .order_by("aliquyam") +/// .max_results(-9) +/// .event("Lorem") +/// .domain("eos") +/// .customer("erat") +/// .custom_field_mask("sadipscing") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Directory { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Directory {} + +impl<'a, C, NC, A> Directory + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Directory { + Directory { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn asps(&'a self) -> AspMethods<'a, C, NC, A> { + AspMethods { hub: &self } + } + pub fn channels(&'a self) -> ChannelMethods<'a, C, NC, A> { + ChannelMethods { hub: &self } + } + pub fn chromeosdevices(&'a self) -> ChromeosdeviceMethods<'a, C, NC, A> { + ChromeosdeviceMethods { hub: &self } + } + pub fn groups(&'a self) -> GroupMethods<'a, C, NC, A> { + GroupMethods { hub: &self } + } + pub fn members(&'a self) -> MemberMethods<'a, C, NC, A> { + MemberMethods { hub: &self } + } + pub fn mobiledevices(&'a self) -> MobiledeviceMethods<'a, C, NC, A> { + MobiledeviceMethods { hub: &self } + } + pub fn notifications(&'a self) -> NotificationMethods<'a, C, NC, A> { + NotificationMethods { hub: &self } + } + pub fn orgunits(&'a self) -> OrgunitMethods<'a, C, NC, A> { + OrgunitMethods { hub: &self } + } + pub fn schemas(&'a self) -> SchemaMethods<'a, C, NC, A> { + SchemaMethods { hub: &self } + } + pub fn tokens(&'a self) -> TokenMethods<'a, C, NC, A> { + TokenMethods { hub: &self } + } + pub fn users(&'a self) -> UserMethods<'a, C, NC, A> { + UserMethods { hub: &self } + } + pub fn verification_codes(&'a self) -> VerificationCodeMethods<'a, C, NC, A> { + VerificationCodeMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// JSON template for name of a user in Directory API. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserName { + /// Full Name + #[serde(alias="fullName")] + pub full_name: String, + /// First Name + #[serde(alias="givenName")] + pub given_name: String, + /// Last Name + #[serde(alias="familyName")] + pub family_name: String, +} + +impl Part for UserName {} + + +/// JSON template for Group resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get groups](struct.GroupGetCall.html) (response) +/// * [aliases insert groups](struct.GroupAliaseInsertCall.html) (none) +/// * [delete groups](struct.GroupDeleteCall.html) (none) +/// * [aliases delete groups](struct.GroupAliaseDeleteCall.html) (none) +/// * [patch groups](struct.GroupPatchCall.html) (request|response) +/// * [list groups](struct.GroupListCall.html) (none) +/// * [aliases list groups](struct.GroupAliaseListCall.html) (none) +/// * [update groups](struct.GroupUpdateCall.html) (request|response) +/// * [insert groups](struct.GroupInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Group { + /// List of non editable aliases (Read-only) + #[serde(alias="nonEditableAliases")] + pub non_editable_aliases: Option>, + /// Kind of resource this is. + pub kind: Option, + /// Description of the group + pub description: Option, + /// Is the group created by admin (Read-only) * + #[serde(alias="adminCreated")] + pub admin_created: Option, + /// Group direct members count + #[serde(alias="directMembersCount")] + pub direct_members_count: Option, + /// Email of Group + pub email: Option, + /// ETag of the resource. + pub etag: Option, + /// List of aliases (Read-only) + pub aliases: Option>, + /// Unique identifier of Group (Read-only) + pub id: Option, + /// Group name + pub name: Option, +} + +impl RequestValue for Group {} +impl Resource for Group {} +impl ResponseResult for Group {} + + +/// Template for a notification resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete notifications](struct.NotificationDeleteCall.html) (none) +/// * [update notifications](struct.NotificationUpdateCall.html) (request|response) +/// * [patch notifications](struct.NotificationPatchCall.html) (request|response) +/// * [get notifications](struct.NotificationGetCall.html) (response) +/// * [list notifications](struct.NotificationListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Notification { + /// Body of the notification (Read-only) + pub body: Option, + /// The type of the resource. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Time at which notification was sent (Read-only) + #[serde(alias="sendTime")] + pub send_time: Option, + /// no description provided + #[serde(alias="notificationId")] + pub notification_id: Option, + /// Address from which the notification is received (Read-only) + #[serde(alias="fromAddress")] + pub from_address: Option, + /// Boolean indicating whether the notification is unread or not. + #[serde(alias="isUnread")] + pub is_unread: Option, + /// Subject of the notification (Read-only) + pub subject: Option, +} + +impl RequestValue for Notification {} +impl Resource for Notification {} +impl ResponseResult for Notification {} + + +/// JSON template for FieldSpec resource for Schemas in Directory API. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SchemaFieldSpec { + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// Read ACLs on the field specifying who can view values of this field. Valid values are "ALL_DOMAIN_USERS" and "ADMINS_AND_SELF". + #[serde(alias="readAccessType")] + pub read_access_type: String, + /// Type of the field. + #[serde(alias="fieldType")] + pub field_type: String, + /// Boolean specifying whether the field is indexed or not. + pub indexed: bool, + /// Name of the field. + #[serde(alias="fieldName")] + pub field_name: String, + /// Indexing spec for a numeric field. By default, only exact match queries will be supported for numeric fields. Setting the numericIndexingSpec allows range queries to be supported. + #[serde(alias="numericIndexingSpec")] + pub numeric_indexing_spec: SchemaFieldSpecNumericIndexingSpec, + /// Unique identifier of Field (Read-only) + #[serde(alias="fieldId")] + pub field_id: String, + /// Boolean specifying whether this is a multi-valued field or not. + #[serde(alias="multiValued")] + pub multi_valued: bool, +} + +impl Part for SchemaFieldSpec {} + + +/// JSON template for Member resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch members](struct.MemberPatchCall.html) (request|response) +/// * [list members](struct.MemberListCall.html) (none) +/// * [insert members](struct.MemberInsertCall.html) (request|response) +/// * [get members](struct.MemberGetCall.html) (response) +/// * [delete members](struct.MemberDeleteCall.html) (none) +/// * [update members](struct.MemberUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Member { + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Role of member + pub role: Option, + /// Type of member (Immutable) + #[serde(alias="type")] + pub type_: Option, + /// Email of member (Read-only) + pub email: Option, + /// Unique identifier of customer member (Read-only) Unique identifier of group (Read-only) Unique identifier of member (Read-only) + pub id: Option, +} + +impl RequestValue for Member {} +impl Resource for Member {} +impl ResponseResult for Member {} + + +/// JSON response template for List Organization Units operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list orgunits](struct.OrgunitListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OrgUnits { + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of user objects. + #[serde(alias="organizationUnits")] + pub organization_units: Vec, +} + +impl ResponseResult for OrgUnits {} + + +/// JSON template for token resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list tokens](struct.TokenListCall.html) (none) +/// * [delete tokens](struct.TokenDeleteCall.html) (none) +/// * [get tokens](struct.TokenGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Token { + /// A list of authorization scopes the application is granted. + pub scopes: Vec, + /// The type of the API resource. This is always admin#directory#token. + pub kind: String, + /// The Client ID of the application the token is issued to. + #[serde(alias="clientId")] + pub client_id: String, + /// Whether the token is issued to an installed application. The value is true if the application is installed to a desktop or mobile device. + #[serde(alias="nativeApp")] + pub native_app: bool, + /// The displayable name of the application the token is issued to. + #[serde(alias="displayText")] + pub display_text: String, + /// ETag of the resource. + pub etag: String, + /// Whether the application is registered with Google. The value is true if the application has an anonymous Client ID. + pub anonymous: bool, + /// The unique ID of the user that issued the token. + #[serde(alias="userKey")] + pub user_key: String, +} + +impl Resource for Token {} +impl ResponseResult for Token {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list asps](struct.AspListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Asps { + /// A list of ASP resources. + pub items: Vec, + /// The type of the API resource. This is always admin#directory#aspList. + pub kind: String, + /// ETag of the resource. + pub etag: String, +} + +impl ResponseResult for Asps {} + + +/// An notification channel used to watch for resource changes. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [watch users](struct.UserWatchCall.html) (request|response) +/// * [stop channels](struct.ChannelStopCall.html) (request) +/// * [aliases watch users](struct.UserAliaseWatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Channel { + /// A version-specific identifier for the watched resource. + #[serde(alias="resourceUri")] + pub resource_uri: Option, + /// Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". + pub kind: Option, + /// An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. + #[serde(alias="resourceId")] + pub resource_id: Option, + /// A UUID or similar unique string that identifies this channel. + pub id: Option, + /// An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. + pub token: Option, + /// Additional parameters controlling delivery channel behavior. Optional. + pub params: Option>, + /// Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. + pub expiration: Option, + /// The address where notifications are delivered for this channel. + pub address: Option, + /// The type of delivery mechanism used for this channel. + #[serde(alias="type")] + pub type_: Option, + /// A Boolean value to indicate whether payload is wanted. Optional. + pub payload: Option, +} + +impl RequestValue for Channel {} +impl Resource for Channel {} +impl ResponseResult for Channel {} + + +/// JSON template for Schema resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get schemas](struct.SchemaGetCall.html) (response) +/// * [insert schemas](struct.SchemaInsertCall.html) (request|response) +/// * [patch schemas](struct.SchemaPatchCall.html) (request|response) +/// * [delete schemas](struct.SchemaDeleteCall.html) (none) +/// * [list schemas](struct.SchemaListCall.html) (none) +/// * [update schemas](struct.SchemaUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Schema { + /// Fields of Schema + pub fields: Option>, + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Unique identifier of Schema (Read-only) + #[serde(alias="schemaId")] + pub schema_id: Option, + /// Schema name + #[serde(alias="schemaName")] + pub schema_name: Option, +} + +impl RequestValue for Schema {} +impl Resource for Schema {} +impl ResponseResult for Schema {} + + +/// The template that returns individual ASP (Access Code) data. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list asps](struct.AspListCall.html) (none) +/// * [delete asps](struct.AspDeleteCall.html) (none) +/// * [get asps](struct.AspGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Asp { + /// The type of the API resource. This is always admin#directory#asp. + pub kind: String, + /// ETag of the ASP. + pub etag: String, + /// The name of the application that the user, represented by their userId, entered when the ASP was created. + pub name: String, + /// The unique ID of the ASP. + #[serde(alias="codeId")] + pub code_id: i32, + /// The time when the ASP was last used. Expressed in Unix time format. + #[serde(alias="lastTimeUsed")] + pub last_time_used: String, + /// The unique ID of the user who issued the ASP. + #[serde(alias="userKey")] + pub user_key: String, + /// The time when the ASP was created. Expressed in Unix time format. + #[serde(alias="creationTime")] + pub creation_time: String, +} + +impl Resource for Asp {} +impl ResponseResult for Asp {} + + +/// JSON response template for List tokens operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list tokens](struct.TokenListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Tokens { + /// A list of Token resources. + pub items: Vec, + /// The type of the API resource. This is always admin#directory#tokenList. + pub kind: String, + /// ETag of the resource. + pub etag: String, +} + +impl ResponseResult for Tokens {} + + +/// Template for notifications list response. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list notifications](struct.NotificationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Notifications { + /// Token for fetching the next page of notifications. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of notifications in this page. + pub items: Vec, + /// The type of the resource. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// Number of unread notification for the domain. + #[serde(alias="unreadNotificationsCount")] + pub unread_notifications_count: i32, +} + +impl ResponseResult for Notifications {} + + +/// JSON template for Chrome Os Device resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get chromeosdevices](struct.ChromeosdeviceGetCall.html) (response) +/// * [update chromeosdevices](struct.ChromeosdeviceUpdateCall.html) (request|response) +/// * [patch chromeosdevices](struct.ChromeosdevicePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ChromeOsDevice { + /// List of recent device users, in descending order by last login time (Read-only) + #[serde(alias="recentUsers")] + pub recent_users: Option>, + /// Chromebook Mac Address on wifi network interface (Read-only) + #[serde(alias="macAddress")] + pub mac_address: Option, + /// Chromebook serial number (Read-only) + #[serde(alias="serialNumber")] + pub serial_number: Option, + /// Date and time the device was last synchronized with the policy settings in the Google Apps administrator control panel (Read-only) + #[serde(alias="lastSync")] + pub last_sync: Option, + /// Chromebook order number (Read-only) + #[serde(alias="orderNumber")] + pub order_number: Option, + /// Mobile Equipment identifier for the 3G mobile card in the Chromebook (Read-only) + pub meid: Option, + /// Address or location of the device as noted by the administrator + #[serde(alias="annotatedLocation")] + pub annotated_location: Option, + /// User of the device + #[serde(alias="annotatedUser")] + pub annotated_user: Option, + /// Chromebook platform version (Read-only) + #[serde(alias="platformVersion")] + pub platform_version: Option, + /// List of active time ranges (Read-only) + #[serde(alias="activeTimeRanges")] + pub active_time_ranges: Option>, + /// Unique identifier of Chrome OS Device (Read-only) + #[serde(alias="deviceId")] + pub device_id: Option, + /// Chromebook Mac Address on ethernet network interface (Read-only) + #[serde(alias="ethernetMacAddress")] + pub ethernet_mac_address: Option, + /// Chromebook Os Version (Read-only) + #[serde(alias="osVersion")] + pub os_version: Option, + /// Chromebook firmware version (Read-only) + #[serde(alias="firmwareVersion")] + pub firmware_version: Option, + /// Date and time the device was last enrolled (Read-only) + #[serde(alias="lastEnrollmentTime")] + pub last_enrollment_time: Option, + /// Kind of resource this is. + pub kind: Option, + /// Notes added by the administrator + pub notes: Option, + /// Will Chromebook auto renew after support end date (Read-only) + #[serde(alias="willAutoRenew")] + pub will_auto_renew: Option, + /// Chromebook boot mode (Read-only) + #[serde(alias="bootMode")] + pub boot_mode: Option, + /// ETag of the resource. + pub etag: Option, + /// status of the device (Read-only) + pub status: Option, + /// OrgUnit of the device + #[serde(alias="orgUnitPath")] + pub org_unit_path: Option, + /// Chromebook Model (Read-only) + pub model: Option, + /// Final date the device will be supported (Read-only) + #[serde(alias="supportEndDate")] + pub support_end_date: Option, +} + +impl RequestValue for ChromeOsDevice {} +impl Resource for ChromeOsDevice {} +impl ResponseResult for ChromeOsDevice {} + + +/// JSON template for User object in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [photos patch users](struct.UserPhotoPatchCall.html) (none) +/// * [aliases delete users](struct.UserAliaseDeleteCall.html) (none) +/// * [undelete users](struct.UserUndeleteCall.html) (none) +/// * [photos get users](struct.UserPhotoGetCall.html) (none) +/// * [update users](struct.UserUpdateCall.html) (request|response) +/// * [aliases watch users](struct.UserAliaseWatchCall.html) (none) +/// * [insert users](struct.UserInsertCall.html) (request|response) +/// * [photos delete users](struct.UserPhotoDeleteCall.html) (none) +/// * [patch users](struct.UserPatchCall.html) (request|response) +/// * [photos update users](struct.UserPhotoUpdateCall.html) (none) +/// * [watch users](struct.UserWatchCall.html) (none) +/// * [get users](struct.UserGetCall.html) (response) +/// * [aliases insert users](struct.UserAliaseInsertCall.html) (none) +/// * [make admin users](struct.UserMakeAdminCall.html) (none) +/// * [aliases list users](struct.UserAliaseListCall.html) (none) +/// * [list users](struct.UserListCall.html) (none) +/// * [delete users](struct.UserDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct User { + /// no description provided + pub addresses: Option, + /// no description provided + pub phones: Option, + /// Boolean indicating if the user is delegated admin (Read-only) + #[serde(alias="isDelegatedAdmin")] + pub is_delegated_admin: Option, + /// Indicates if user is suspended + pub suspended: Option, + /// Unique identifier of User (Read-only) + pub id: Option, + /// List of aliases (Read-only) + pub aliases: Option>, + /// List of non editable aliases (Read-only) + #[serde(alias="nonEditableAliases")] + pub non_editable_aliases: Option>, + /// Custom fields of the user. + #[serde(alias="customSchemas")] + pub custom_schemas: Option>, + /// no description provided + #[serde(alias="deletionTime")] + pub deletion_time: Option, + /// Suspension reason if user is suspended (Read-only) + #[serde(alias="suspensionReason")] + pub suspension_reason: Option, + /// Photo Url of the user (Read-only) + #[serde(alias="thumbnailPhotoUrl")] + pub thumbnail_photo_url: Option, + /// Boolean indicating if the user is admin (Read-only) + #[serde(alias="isAdmin")] + pub is_admin: Option, + /// no description provided + pub relations: Option, + /// Boolean indicating if user is included in Global Address List + #[serde(alias="includeInGlobalAddressList")] + pub include_in_global_address_list: Option, + /// ETag of the resource. + pub etag: Option, + /// User's last login time. (Read-only) + #[serde(alias="lastLoginTime")] + pub last_login_time: Option, + /// OrgUnit of User + #[serde(alias="orgUnitPath")] + pub org_unit_path: Option, + /// Indicates if user has agreed to terms (Read-only) + #[serde(alias="agreedToTerms")] + pub agreed_to_terms: Option, + /// no description provided + #[serde(alias="externalIds")] + pub external_ids: Option, + /// Boolean indicating if ip is whitelisted + #[serde(alias="ipWhitelisted")] + pub ip_whitelisted: Option, + /// Kind of resource this is. + pub kind: Option, + /// Is mailbox setup (Read-only) + #[serde(alias="isMailboxSetup")] + pub is_mailbox_setup: Option, + /// User's password + pub password: Option, + /// no description provided + pub emails: Option, + /// no description provided + pub organizations: Option, + /// username of User + #[serde(alias="primaryEmail")] + pub primary_email: Option, + /// Hash function name for password. Supported are MD5, SHA-1 and crypt + #[serde(alias="hashFunction")] + pub hash_function: Option, + /// User's name + pub name: Option, + /// no description provided + pub notes: Option, + /// User's Google account creation time. (Read-only) + #[serde(alias="creationTime")] + pub creation_time: Option, + /// no description provided + pub websites: Option, + /// Boolean indicating if the user should change password in next login + #[serde(alias="changePasswordAtNextLogin")] + pub change_password_at_next_login: Option, + /// no description provided + pub ims: Option, + /// CustomerId of User (Read-only) + #[serde(alias="customerId")] + pub customer_id: Option, +} + +impl RequestValue for User {} +impl Resource for User {} +impl ResponseResult for User {} + + +/// JSON response template for List Groups operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list groups](struct.GroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Groups { + /// Token used to access next page of this result. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of group objects. + pub groups: Vec, +} + +impl ResponseResult for Groups {} + + +/// List of recent device users, in descending order by last login time (Read-only) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ChromeOsDeviceRecentUsers { + /// The type of the user + #[serde(alias="type")] + pub type_: String, + /// Email address of the user. Present only if the user type is managed + pub email: String, +} + +impl NestedType for ChromeOsDeviceRecentUsers {} +impl Part for ChromeOsDeviceRecentUsers {} + + +/// List of applications installed on Mobile Device +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MobileDeviceApplications { + /// Version code of application + #[serde(alias="versionCode")] + pub version_code: i32, + /// Package name of application + #[serde(alias="packageName")] + pub package_name: String, + /// Display name of application + #[serde(alias="displayName")] + pub display_name: String, + /// Version name of application + #[serde(alias="versionName")] + pub version_name: String, + /// List of Permissions for application + pub permission: Vec, +} + +impl NestedType for MobileDeviceApplications {} +impl Part for MobileDeviceApplications {} + + +/// JSON template for a set of custom properties (i.e. all fields in a particular schema) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserCustomProperties(HashMap); + +impl Part for UserCustomProperties {} + + +/// JSON response template for List Members operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list members](struct.MemberListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Members { + /// Token used to access next page of this result. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of member objects. + pub members: Vec, +} + +impl ResponseResult for Members {} + + +/// JSON request template to undelete a user in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [undelete users](struct.UserUndeleteCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UserUndelete { + /// OrgUnit of User + #[serde(alias="orgUnitPath")] + pub org_unit_path: Option, +} + +impl RequestValue for UserUndelete {} + + +/// JSON response template for List verification codes operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list verification codes](struct.VerificationCodeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VerificationCodes { + /// A list of verification code resources. + pub items: Vec, + /// The type of the resource. This is always admin#directory#verificationCodesList. + pub kind: String, + /// ETag of the resource. + pub etag: String, +} + +impl ResponseResult for VerificationCodes {} + + +/// JSON template for Alias object in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aliases insert users](struct.UserAliaseInsertCall.html) (request|response) +/// * [aliases insert groups](struct.GroupAliaseInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Alias { + /// A alias email + pub alias: Option, + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Group's primary email (Read-only) User's primary email (Read-only) + #[serde(alias="primaryEmail")] + pub primary_email: Option, + /// Unique id of the group (Read-only) Unique id of the user (Read-only) + pub id: Option, +} + +impl RequestValue for Alias {} +impl ResponseResult for Alias {} + + +/// JSON response template for List Mobile Devices operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list mobiledevices](struct.MobiledeviceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MobileDevices { + /// Token used to access next page of this result. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of Mobile Device objects. + pub mobiledevices: Vec, +} + +impl ResponseResult for MobileDevices {} + + +/// List of active time ranges (Read-only) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ChromeOsDeviceActiveTimeRanges { + /// Date of usage + pub date: String, + /// Duration in milliseconds + #[serde(alias="activeTime")] + pub active_time: i32, +} + +impl NestedType for ChromeOsDeviceActiveTimeRanges {} +impl Part for ChromeOsDeviceActiveTimeRanges {} + + +/// JSON template for Photo object in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [photos update users](struct.UserPhotoUpdateCall.html) (request|response) +/// * [photos patch users](struct.UserPhotoPatchCall.html) (request|response) +/// * [photos get users](struct.UserPhotoGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserPhoto { + /// Mime Type of the photo + #[serde(alias="mimeType")] + pub mime_type: Option, + /// Kind of resource this is. + pub kind: Option, + /// Base64 encoded photo data + #[serde(alias="photoData")] + pub photo_data: Option, + /// Height in pixels of the photo + pub height: Option, + /// Width in pixels of the photo + pub width: Option, + /// ETag of the resource. + pub etag: Option, + /// Primary email of User (Read-only) + #[serde(alias="primaryEmail")] + pub primary_email: Option, + /// Unique identifier of User (Read-only) + pub id: Option, +} + +impl RequestValue for UserPhoto {} +impl ResponseResult for UserPhoto {} + + +/// JSON request template for firing commands on Mobile Device in Directory Devices API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [action mobiledevices](struct.MobiledeviceActionCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct MobileDeviceAction { + /// Action to be taken on the Mobile Device + pub action: Option, +} + +impl RequestValue for MobileDeviceAction {} + + +/// JSON request template for setting/revoking admin status of a user in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [make admin users](struct.UserMakeAdminCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UserMakeAdmin { + /// Boolean indicating new admin status of the user + pub status: Option, +} + +impl RequestValue for UserMakeAdmin {} + + +/// JSON response template for List Users operation in Apps Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list users](struct.UserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Users { + /// Token used to access next page of this result. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// Event that triggered this response (only used in case of Push Response) + pub trigger_event: String, + /// List of user objects. + pub users: Vec, +} + +impl ResponseResult for Users {} + + +/// JSON template for Mobile Device resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get mobiledevices](struct.MobiledeviceGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MobileDevice { + /// Mobile Device Kernel version (Read-only) + #[serde(alias="kernelVersion")] + pub kernel_version: String, + /// Date and time the device was last synchronized with the policy settings in the Google Apps administrator control panel (Read-only) + #[serde(alias="lastSync")] + pub last_sync: String, + /// Mobile Device compromised status (Read-only) + #[serde(alias="deviceCompromisedStatus")] + pub device_compromised_status: String, + /// Unique identifier of Mobile Device (Read-only) + #[serde(alias="resourceId")] + pub resource_id: String, + /// Mobile Device MEID number (Read-only) + pub meid: String, + /// The default locale used on the Mobile Device (Read-only) + #[serde(alias="defaultLanguage")] + pub default_language: String, + /// Mobile Device Build number (Read-only) + #[serde(alias="buildNumber")] + pub build_number: String, + /// List of applications installed on Mobile Device + pub applications: Vec, + /// Mobile Device serial number (Read-only) + #[serde(alias="deviceId")] + pub device_id: String, + /// Mobile Device IMEI number (Read-only) + pub imei: String, + /// Mobile Device user agent + #[serde(alias="userAgent")] + pub user_agent: String, + /// Mobile Device Baseband version (Read-only) + #[serde(alias="basebandVersion")] + pub baseband_version: String, + /// Kind of resource this is. + pub kind: String, + /// List of owner user's names (Read-only) + pub name: Vec, + /// Date and time the device was first synchronized with the policy settings in the Google Apps administrator control panel (Read-only) + #[serde(alias="firstSync")] + pub first_sync: String, + /// Name of the mobile operating system + pub os: String, + /// Mobile Device SSN or Serial Number (Read-only) + #[serde(alias="serialNumber")] + pub serial_number: String, + /// Mobile Device Hardware Id (Read-only) + #[serde(alias="hardwareId")] + pub hardware_id: String, + /// Mobile Device mobile or network operator (if available) (Read-only) + #[serde(alias="networkOperator")] + pub network_operator: String, + /// ETag of the resource. + pub etag: String, + /// Status of the device (Read-only) + pub status: String, + /// Boolean indicating if this account is on owner/primary profile or not (Read-only) + #[serde(alias="managedAccountIsOnOwnerProfile")] + pub managed_account_is_on_owner_profile: bool, + /// Name of the model of the device + pub model: String, + /// The type of device (Read-only) + #[serde(alias="type")] + pub type_: String, + /// List of owner user's email addresses (Read-only) + pub email: Vec, + /// Mobile Device WiFi MAC address (Read-only) + #[serde(alias="wifiMacAddress")] + pub wifi_mac_address: String, +} + +impl Resource for MobileDevice {} +impl ResponseResult for MobileDevice {} + + +/// JSON response template for List Chrome OS Devices operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list chromeosdevices](struct.ChromeosdeviceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChromeOsDevices { + /// Token used to access next page of this result. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of Chrome OS Device objects. + pub chromeosdevices: Vec, + /// ETag of the resource. + pub etag: String, + /// Kind of resource this is. + pub kind: String, +} + +impl ResponseResult for ChromeOsDevices {} + + +/// JSON template for Org Unit resource in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch orgunits](struct.OrgunitPatchCall.html) (request|response) +/// * [get orgunits](struct.OrgunitGetCall.html) (response) +/// * [update orgunits](struct.OrgunitUpdateCall.html) (request|response) +/// * [insert orgunits](struct.OrgunitInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrgUnit { + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Path of parent OrgUnit + #[serde(alias="parentOrgUnitPath")] + pub parent_org_unit_path: Option, + /// Name of OrgUnit + pub name: Option, + /// Should block inheritance + #[serde(alias="blockInheritance")] + pub block_inheritance: Option, + /// Path of OrgUnit + #[serde(alias="orgUnitPath")] + pub org_unit_path: Option, + /// Description of OrgUnit + pub description: Option, +} + +impl RequestValue for OrgUnit {} +impl Resource for OrgUnit {} +impl ResponseResult for OrgUnit {} + + +/// JSON template for verification codes in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [invalidate verification codes](struct.VerificationCodeInvalidateCall.html) (none) +/// * [list verification codes](struct.VerificationCodeListCall.html) (none) +/// * [generate verification codes](struct.VerificationCodeGenerateCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VerificationCode { + /// The type of the resource. This is always admin#directory#verificationCode. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// The obfuscated unique ID of the user. + #[serde(alias="userId")] + pub user_id: Option, + /// A current verification code for the user. Invalidated or used verification codes are not returned as part of the result. + #[serde(alias="verificationCode")] + pub verification_code: Option, +} + +impl Resource for VerificationCode {} + + +/// Indexing spec for a numeric field. By default, only exact match queries will be supported for numeric fields. Setting the numericIndexingSpec allows range queries to be supported. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SchemaFieldSpecNumericIndexingSpec { + /// Maximum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant. + #[serde(alias="maxValue")] + pub max_value: f64, + /// Minimum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant. + #[serde(alias="minValue")] + pub min_value: f64, +} + +impl NestedType for SchemaFieldSpecNumericIndexingSpec {} +impl Part for SchemaFieldSpecNumericIndexingSpec {} + + +/// JSON response template for List Schema operation in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list schemas](struct.SchemaListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Schemas { + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of UserSchema objects. + pub schemas: Vec, +} + +impl ResponseResult for Schemas {} + + +/// JSON response template to list aliases in Directory API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aliases list users](struct.UserAliaseListCall.html) (response) +/// * [aliases list groups](struct.GroupAliaseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Aliases { + /// Kind of resource this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// List of alias objects. + pub aliases: Vec, +} + +impl ResponseResult for Aliases {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *token* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.tokens(); +/// # } +/// ``` +pub struct TokenMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TokenMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TokenMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Get information about an access token issued by a user. + pub fn get(&self, user_key: &str, client_id: &str) -> TokenGetCall<'a, C, NC, A> { + TokenGetCall { + hub: self.hub, + _user_key: user_key.to_string(), + _client_id: client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the set of tokens specified user has issued to 3rd party applications. + pub fn list(&self, user_key: &str) -> TokenListCall<'a, C, NC, A> { + TokenListCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete all access tokens issued by a user for an application. + pub fn delete(&self, user_key: &str, client_id: &str) -> TokenDeleteCall<'a, C, NC, A> { + TokenDeleteCall { + hub: self.hub, + _user_key: user_key.to_string(), + _client_id: client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *channel* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `stop(...)` +/// // to build up your call. +/// let rb = hub.channels(); +/// # } +/// ``` +pub struct ChannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Stop watching resources through this channel + pub fn stop(&self, request: &Channel) -> ChannelStopCall<'a, C, NC, A> { + ChannelStopCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *orgunit* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.orgunits(); +/// # } +/// ``` +pub struct OrgunitMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for OrgunitMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Add Organization Unit + pub fn insert(&self, request: &OrgUnit, customer_id: &str) -> OrgunitInsertCall<'a, C, NC, A> { + OrgunitInsertCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all Organization Units + pub fn list(&self, customer_id: &str) -> OrgunitListCall<'a, C, NC, A> { + OrgunitListCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _type_: Default::default(), + _org_unit_path: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Organization Unit + pub fn get(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitGetCall<'a, C, NC, A> { + OrgunitGetCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _org_unit_path: org_unit_path.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Organization Unit + pub fn update(&self, request: &OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitUpdateCall<'a, C, NC, A> { + OrgunitUpdateCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _org_unit_path: org_unit_path.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove Organization Unit + pub fn delete(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitDeleteCall<'a, C, NC, A> { + OrgunitDeleteCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _org_unit_path: org_unit_path.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Organization Unit. This method supports patch semantics. + pub fn patch(&self, request: &OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitPatchCall<'a, C, NC, A> { + OrgunitPatchCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _org_unit_path: org_unit_path.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *user* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aliases_delete(...)`, `aliases_insert(...)`, `aliases_list(...)`, `aliases_watch(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `make_admin(...)`, `patch(...)`, `photos_delete(...)`, `photos_get(...)`, `photos_patch(...)`, `photos_update(...)`, `undelete(...)`, `update(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.users(); +/// # } +/// ``` +pub struct UserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// create user. + pub fn insert(&self, request: &User) -> UserInsertCall<'a, C, NC, A> { + UserInsertCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove photos for the user + pub fn photos_delete(&self, user_key: &str) -> UserPhotoDeleteCall<'a, C, NC, A> { + UserPhotoDeleteCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Undelete a deleted user + pub fn undelete(&self, request: &UserUndelete, user_key: &str) -> UserUndeleteCall<'a, C, NC, A> { + UserUndeleteCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// change admin status of a user + pub fn make_admin(&self, request: &UserMakeAdmin, user_key: &str) -> UserMakeAdminCall<'a, C, NC, A> { + UserMakeAdminCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// update user. This method supports patch semantics. + pub fn patch(&self, request: &User, user_key: &str) -> UserPatchCall<'a, C, NC, A> { + UserPatchCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes in users list + pub fn watch(&self, request: &Channel) -> UserWatchCall<'a, C, NC, A> { + UserWatchCall { + hub: self.hub, + _request: request.clone(), + _view_type: Default::default(), + _sort_order: Default::default(), + _show_deleted: Default::default(), + _query: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _event: Default::default(), + _domain: Default::default(), + _customer: Default::default(), + _custom_field_mask: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete user + pub fn delete(&self, user_key: &str) -> UserDeleteCall<'a, C, NC, A> { + UserDeleteCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a photo for the user + pub fn photos_update(&self, request: &UserPhoto, user_key: &str) -> UserPhotoUpdateCall<'a, C, NC, A> { + UserPhotoUpdateCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// retrieve user + pub fn get(&self, user_key: &str) -> UserGetCall<'a, C, NC, A> { + UserGetCall { + hub: self.hub, + _user_key: user_key.to_string(), + _view_type: Default::default(), + _projection: Default::default(), + _custom_field_mask: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a alias for the user + pub fn aliases_insert(&self, request: &Alias, user_key: &str) -> UserAliaseInsertCall<'a, C, NC, A> { + UserAliaseInsertCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve either deleted users or all users in a domain (paginated) + pub fn list(&self) -> UserListCall<'a, C, NC, A> { + UserListCall { + hub: self.hub, + _view_type: Default::default(), + _sort_order: Default::default(), + _show_deleted: Default::default(), + _query: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _event: Default::default(), + _domain: Default::default(), + _customer: Default::default(), + _custom_field_mask: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove a alias for the user + pub fn aliases_delete(&self, user_key: &str, alias: &str) -> UserAliaseDeleteCall<'a, C, NC, A> { + UserAliaseDeleteCall { + hub: self.hub, + _user_key: user_key.to_string(), + _alias: alias.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// update user + pub fn update(&self, request: &User, user_key: &str) -> UserUpdateCall<'a, C, NC, A> { + UserUpdateCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes in user aliases list + pub fn aliases_watch(&self, request: &Channel, user_key: &str) -> UserAliaseWatchCall<'a, C, NC, A> { + UserAliaseWatchCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _event: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all aliases for a user + pub fn aliases_list(&self, user_key: &str) -> UserAliaseListCall<'a, C, NC, A> { + UserAliaseListCall { + hub: self.hub, + _user_key: user_key.to_string(), + _event: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve photo of a user + pub fn photos_get(&self, user_key: &str) -> UserPhotoGetCall<'a, C, NC, A> { + UserPhotoGetCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a photo for the user. This method supports patch semantics. + pub fn photos_patch(&self, request: &UserPhoto, user_key: &str) -> UserPhotoPatchCall<'a, C, NC, A> { + UserPhotoPatchCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *mobiledevice* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `action(...)`, `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.mobiledevices(); +/// # } +/// ``` +pub struct MobiledeviceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MobiledeviceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobiledeviceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Delete Mobile Device + pub fn delete(&self, customer_id: &str, resource_id: &str) -> MobiledeviceDeleteCall<'a, C, NC, A> { + MobiledeviceDeleteCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _resource_id: resource_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Mobile Device + pub fn get(&self, customer_id: &str, resource_id: &str) -> MobiledeviceGetCall<'a, C, NC, A> { + MobiledeviceGetCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _resource_id: resource_id.to_string(), + _projection: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all Mobile Devices of a customer (paginated) + pub fn list(&self, customer_id: &str) -> MobiledeviceListCall<'a, C, NC, A> { + MobiledeviceListCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _sort_order: Default::default(), + _query: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Take action on Mobile Device + pub fn action(&self, request: &MobileDeviceAction, customer_id: &str, resource_id: &str) -> MobiledeviceActionCall<'a, C, NC, A> { + MobiledeviceActionCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _resource_id: resource_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *member* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.members(); +/// # } +/// ``` +pub struct MemberMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MemberMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Update membership of a user in the specified group. + pub fn update(&self, request: &Member, group_key: &str, member_key: &str) -> MemberUpdateCall<'a, C, NC, A> { + MemberUpdateCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _member_key: member_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Group Member + pub fn get(&self, group_key: &str, member_key: &str) -> MemberGetCall<'a, C, NC, A> { + MemberGetCall { + hub: self.hub, + _group_key: group_key.to_string(), + _member_key: member_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add user to the specified group. + pub fn insert(&self, request: &Member, group_key: &str) -> MemberInsertCall<'a, C, NC, A> { + MemberInsertCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update membership of a user in the specified group. This method supports patch semantics. + pub fn patch(&self, request: &Member, group_key: &str, member_key: &str) -> MemberPatchCall<'a, C, NC, A> { + MemberPatchCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _member_key: member_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove membership. + pub fn delete(&self, group_key: &str, member_key: &str) -> MemberDeleteCall<'a, C, NC, A> { + MemberDeleteCall { + hub: self.hub, + _group_key: group_key.to_string(), + _member_key: member_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all members in a group (paginated) + pub fn list(&self, group_key: &str) -> MemberListCall<'a, C, NC, A> { + MemberListCall { + hub: self.hub, + _group_key: group_key.to_string(), + _roles: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *notification* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.notifications(); +/// # } +/// ``` +pub struct NotificationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for NotificationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of notifications. + pub fn list(&self, customer: &str) -> NotificationListCall<'a, C, NC, A> { + NotificationListCall { + hub: self.hub, + _customer: customer.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _language: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a notification + pub fn delete(&self, customer: &str, notification_id: &str) -> NotificationDeleteCall<'a, C, NC, A> { + NotificationDeleteCall { + hub: self.hub, + _customer: customer.to_string(), + _notification_id: notification_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a notification. This method supports patch semantics. + pub fn patch(&self, request: &Notification, customer: &str, notification_id: &str) -> NotificationPatchCall<'a, C, NC, A> { + NotificationPatchCall { + hub: self.hub, + _request: request.clone(), + _customer: customer.to_string(), + _notification_id: notification_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a notification. + pub fn update(&self, request: &Notification, customer: &str, notification_id: &str) -> NotificationUpdateCall<'a, C, NC, A> { + NotificationUpdateCall { + hub: self.hub, + _request: request.clone(), + _customer: customer.to_string(), + _notification_id: notification_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a notification. + pub fn get(&self, customer: &str, notification_id: &str) -> NotificationGetCall<'a, C, NC, A> { + NotificationGetCall { + hub: self.hub, + _customer: customer.to_string(), + _notification_id: notification_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *chromeosdevice* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.chromeosdevices(); +/// # } +/// ``` +pub struct ChromeosdeviceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChromeosdeviceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChromeosdeviceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all Chrome OS Devices of a customer (paginated) + pub fn list(&self, customer_id: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + ChromeosdeviceListCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _sort_order: Default::default(), + _query: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Chrome OS Device. This method supports patch semantics. + pub fn patch(&self, request: &ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdevicePatchCall<'a, C, NC, A> { + ChromeosdevicePatchCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _device_id: device_id.to_string(), + _projection: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Chrome OS Device + pub fn get(&self, customer_id: &str, device_id: &str) -> ChromeosdeviceGetCall<'a, C, NC, A> { + ChromeosdeviceGetCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _device_id: device_id.to_string(), + _projection: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Chrome OS Device + pub fn update(&self, request: &ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + ChromeosdeviceUpdateCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _device_id: device_id.to_string(), + _projection: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *verificationCode* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generate(...)`, `invalidate(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.verification_codes(); +/// # } +/// ``` +pub struct VerificationCodeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for VerificationCodeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> VerificationCodeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Generate new backup verification codes for the user. + pub fn generate(&self, user_key: &str) -> VerificationCodeGenerateCall<'a, C, NC, A> { + VerificationCodeGenerateCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Invalidate the current backup verification codes for the user. + pub fn invalidate(&self, user_key: &str) -> VerificationCodeInvalidateCall<'a, C, NC, A> { + VerificationCodeInvalidateCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the current set of valid backup verification codes for the specified user. + pub fn list(&self, user_key: &str) -> VerificationCodeListCall<'a, C, NC, A> { + VerificationCodeListCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *group* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aliases_delete(...)`, `aliases_insert(...)`, `aliases_list(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.groups(); +/// # } +/// ``` +pub struct GroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Group + pub fn get(&self, group_key: &str) -> GroupGetCall<'a, C, NC, A> { + GroupGetCall { + hub: self.hub, + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all groups in a domain (paginated) + pub fn list(&self) -> GroupListCall<'a, C, NC, A> { + GroupListCall { + hub: self.hub, + _user_key: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _domain: Default::default(), + _customer: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all aliases for a group + pub fn aliases_list(&self, group_key: &str) -> GroupAliaseListCall<'a, C, NC, A> { + GroupAliaseListCall { + hub: self.hub, + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Group. This method supports patch semantics. + pub fn patch(&self, request: &Group, group_key: &str) -> GroupPatchCall<'a, C, NC, A> { + GroupPatchCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update Group + pub fn update(&self, request: &Group, group_key: &str) -> GroupUpdateCall<'a, C, NC, A> { + GroupUpdateCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete Group + pub fn delete(&self, group_key: &str) -> GroupDeleteCall<'a, C, NC, A> { + GroupDeleteCall { + hub: self.hub, + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a alias for the group + pub fn aliases_insert(&self, request: &Alias, group_key: &str) -> GroupAliaseInsertCall<'a, C, NC, A> { + GroupAliaseInsertCall { + hub: self.hub, + _request: request.clone(), + _group_key: group_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove a alias for the group + pub fn aliases_delete(&self, group_key: &str, alias: &str) -> GroupAliaseDeleteCall<'a, C, NC, A> { + GroupAliaseDeleteCall { + hub: self.hub, + _group_key: group_key.to_string(), + _alias: alias.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create Group + pub fn insert(&self, request: &Group) -> GroupInsertCall<'a, C, NC, A> { + GroupInsertCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *asp* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.asps(); +/// # } +/// ``` +pub struct AspMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AspMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AspMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Delete an ASP issued by a user. + pub fn delete(&self, user_key: &str, code_id: i32) -> AspDeleteCall<'a, C, NC, A> { + AspDeleteCall { + hub: self.hub, + _user_key: user_key.to_string(), + _code_id: code_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the ASPs issued by a user. + pub fn list(&self, user_key: &str) -> AspListCall<'a, C, NC, A> { + AspListCall { + hub: self.hub, + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about an ASP issued by a user. + pub fn get(&self, user_key: &str, code_id: i32) -> AspGetCall<'a, C, NC, A> { + AspGetCall { + hub: self.hub, + _user_key: user_key.to_string(), + _code_id: code_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *schema* resources. +/// It is not used directly, but through the `Directory` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_directory" as admin1_directory; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_directory::Directory; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Directory::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.schemas(); +/// # } +/// ``` +pub struct SchemaMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SchemaMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all schemas for a customer + pub fn list(&self, customer_id: &str) -> SchemaListCall<'a, C, NC, A> { + SchemaListCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve schema + pub fn get(&self, customer_id: &str, schema_key: &str) -> SchemaGetCall<'a, C, NC, A> { + SchemaGetCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _schema_key: schema_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update schema. This method supports patch semantics. + pub fn patch(&self, request: &Schema, customer_id: &str, schema_key: &str) -> SchemaPatchCall<'a, C, NC, A> { + SchemaPatchCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _schema_key: schema_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create schema. + pub fn insert(&self, request: &Schema, customer_id: &str) -> SchemaInsertCall<'a, C, NC, A> { + SchemaInsertCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete schema + pub fn delete(&self, customer_id: &str, schema_key: &str) -> SchemaDeleteCall<'a, C, NC, A> { + SchemaDeleteCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _schema_key: schema_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update schema + pub fn update(&self, request: &Schema, customer_id: &str, schema_key: &str) -> SchemaUpdateCall<'a, C, NC, A> { + SchemaUpdateCall { + hub: self.hub, + _request: request.clone(), + _customer_id: customer_id.to_string(), + _schema_key: schema_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Get information about an access token issued by a user. +/// +/// A builder for the *get* method supported by a *token* resource. +/// It is not used directly, but through a `TokenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tokens().get("userKey", "clientId") +/// .doit(); +/// # } +/// ``` +pub struct TokenGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TokenGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TokenGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Token)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.tokens.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("clientId", self._client_id.to_string())); + for &field in ["alt", "userKey", "clientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{clientId}", "clientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "clientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> TokenGetCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Client ID of the application the token is issued to. + pub fn client_id(mut self, new_value: &str) -> TokenGetCall<'a, C, NC, A> { + self._client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TokenGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TokenGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TokenGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the set of tokens specified user has issued to 3rd party applications. +/// +/// A builder for the *list* method supported by a *token* resource. +/// It is not used directly, but through a `TokenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tokens().list("userKey") +/// .doit(); +/// # } +/// ``` +pub struct TokenListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TokenListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TokenListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Tokens)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.tokens.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> TokenListCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TokenListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TokenListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TokenListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete all access tokens issued by a user for an application. +/// +/// A builder for the *delete* method supported by a *token* resource. +/// It is not used directly, but through a `TokenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tokens().delete("userKey", "clientId") +/// .doit(); +/// # } +/// ``` +pub struct TokenDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TokenDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TokenDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.tokens.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("clientId", self._client_id.to_string())); + for &field in ["userKey", "clientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{clientId}", "clientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "clientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> TokenDeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Client ID of the application the token is issued to. + pub fn client_id(mut self, new_value: &str) -> TokenDeleteCall<'a, C, NC, A> { + self._client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TokenDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TokenDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TokenDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Stop watching resources through this channel +/// +/// A builder for the *stop* method supported by a *channel* resource. +/// It is not used directly, but through a `ChannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.channels().stop(&req) +/// .doit(); +/// # } +/// ``` +pub struct ChannelStopCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Channel, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChannelStopCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelStopCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "admin.channels.stop", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in [].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1//admin/directory_v1/channels/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ChannelStopCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add Organization Unit +/// +/// A builder for the *insert* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::OrgUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: OrgUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().insert(&req, "customerId") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: OrgUnit, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrgUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + for &field in ["alt", "customerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &OrgUnit) -> OrgunitInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitInsertCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all Organization Units +/// +/// A builder for the *list* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().list("customerId") +/// .type_("dolore") +/// .org_unit_path("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _type_: Option, + _org_unit_path: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrgUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if let Some(value) = self._type_ { + params.push(("type", value.to_string())); + } + if let Some(value) = self._org_unit_path { + params.push(("orgUnitPath", value.to_string())); + } + for &field in ["alt", "customerId", "type", "orgUnitPath"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitListCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *type* query property to the given value. + /// + /// + /// Whether to return all sub-organizations or just immediate children + pub fn type_(mut self, new_value: &str) -> OrgunitListCall<'a, C, NC, A> { + self._type_ = Some(new_value.to_string()); + self + } + /// Sets the *org unit path* query property to the given value. + /// + /// + /// the URL-encoded organization unit + pub fn org_unit_path(mut self, new_value: &str) -> OrgunitListCall<'a, C, NC, A> { + self._org_unit_path = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve Organization Unit +/// +/// A builder for the *get* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().get("customerId", "orgUnitPath") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _org_unit_path: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrgUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if self._org_unit_path.len() > 0 { + let mut s = String::new(); + for f in self._org_unit_path.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orgUnitPath", s)); + } + for &field in ["alt", "customerId", "orgUnitPath"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits{/orgUnitPath*}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{/orgUnitPath*}", "orgUnitPath")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "orgUnitPath"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitGetCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Append the given value to the *org unit path* path property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Full path of the organization unit + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitGetCall<'a, C, NC, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Organization Unit +/// +/// A builder for the *update* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::OrgUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: OrgUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().update(&req, "customerId", "orgUnitPath") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: OrgUnit, + _customer_id: String, + _org_unit_path: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrgUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if self._org_unit_path.len() > 0 { + let mut s = String::new(); + for f in self._org_unit_path.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orgUnitPath", s)); + } + for &field in ["alt", "customerId", "orgUnitPath"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits{/orgUnitPath*}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{/orgUnitPath*}", "orgUnitPath")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "orgUnitPath"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &OrgUnit) -> OrgunitUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Append the given value to the *org unit path* path property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Full path of the organization unit + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, NC, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove Organization Unit +/// +/// A builder for the *delete* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().delete("customerId", "orgUnitPath") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _org_unit_path: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if self._org_unit_path.len() > 0 { + let mut s = String::new(); + for f in self._org_unit_path.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orgUnitPath", s)); + } + for &field in ["customerId", "orgUnitPath"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits{/orgUnitPath*}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{/orgUnitPath*}", "orgUnitPath")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "orgUnitPath"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Append the given value to the *org unit path* path property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Full path of the organization unit + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, NC, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Organization Unit. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *orgunit* resource. +/// It is not used directly, but through a `OrgunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::OrgUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: OrgUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orgunits().patch(&req, "customerId", "orgUnitPath") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: OrgUnit, + _customer_id: String, + _org_unit_path: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OrgunitPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OrgunitPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrgUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.orgunits.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if self._org_unit_path.len() > 0 { + let mut s = String::new(); + for f in self._org_unit_path.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orgUnitPath", s)); + } + for &field in ["alt", "customerId", "orgUnitPath"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits{/orgUnitPath*}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{/orgUnitPath*}", "orgUnitPath")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "orgUnitPath"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &OrgUnit) -> OrgunitPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Append the given value to the *org unit path* path property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Full path of the organization unit + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, NC, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrgunitPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrgunitPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// create user. +/// +/// A builder for the *insert* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: User = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().insert(&req) +/// .doit(); +/// # } +/// ``` +pub struct UserInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &User) -> UserInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove photos for the user +/// +/// A builder for the *photos.delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().photos_delete("userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserPhotoDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserPhotoDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserPhotoDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.photos.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserPhotoDeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserPhotoDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserPhotoDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Undelete a deleted user +/// +/// A builder for the *undelete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::UserUndelete; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserUndelete = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().undelete(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserUndeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: UserUndelete, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserUndeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserUndeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.undelete", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/undelete".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserUndelete) -> UserUndeleteCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The immutable id of the user + pub fn user_key(mut self, new_value: &str) -> UserUndeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUndeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserUndeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserUndeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// change admin status of a user +/// +/// A builder for the *makeAdmin* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::UserMakeAdmin; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserMakeAdmin = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().make_admin(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserMakeAdminCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: UserMakeAdmin, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserMakeAdminCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserMakeAdminCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.makeAdmin", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/makeAdmin".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserMakeAdmin) -> UserMakeAdminCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user as admin + pub fn user_key(mut self, new_value: &str) -> UserMakeAdminCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserMakeAdminCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserMakeAdminCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserMakeAdminCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// update user. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: User = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().patch(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &User) -> UserPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user. If Id, it should match with id of user object + pub fn user_key(mut self, new_value: &str) -> UserPatchCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes in users list +/// +/// A builder for the *watch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().watch(&req) +/// .view_type("consetetur") +/// .sort_order("ut") +/// .show_deleted("ea") +/// .query("sed") +/// .projection("dolor") +/// .page_token("dolor") +/// .order_by("dolor") +/// .max_results(-23) +/// .event("consetetur") +/// .domain("amet.") +/// .customer("voluptua.") +/// .custom_field_mask("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct UserWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Channel, + _view_type: Option, + _sort_order: Option, + _show_deleted: Option, + _query: Option, + _projection: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _event: Option, + _domain: Option, + _customer: Option, + _custom_field_mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + if let Some(value) = self._view_type { + params.push(("viewType", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._event { + params.push(("event", value.to_string())); + } + if let Some(value) = self._domain { + params.push(("domain", value.to_string())); + } + if let Some(value) = self._customer { + params.push(("customer", value.to_string())); + } + if let Some(value) = self._custom_field_mask { + params.push(("customFieldMask", value.to_string())); + } + for &field in ["alt", "viewType", "sortOrder", "showDeleted", "query", "projection", "pageToken", "orderBy", "maxResults", "event", "domain", "customer", "customFieldMask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> UserWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *view type* query property to the given value. + /// + /// + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + pub fn view_type(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Whether to return results in ascending or descending order. + pub fn sort_order(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// If set to true retrieves the list of deleted users. Default is false + pub fn show_deleted(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._show_deleted = Some(new_value.to_string()); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users + pub fn query(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// What subset of fields to fetch for this user. + pub fn projection(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Column to use for sorting results + pub fn order_by(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 100. Max allowed is 500 + pub fn max_results(mut self, new_value: i32) -> UserWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *event* query property to the given value. + /// + /// + /// Event on which subscription is intended (if subscribing) + pub fn event(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._event = Some(new_value.to_string()); + self + } + /// Sets the *domain* query property to the given value. + /// + /// + /// Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. + pub fn domain(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._domain = Some(new_value.to_string()); + self + } + /// Sets the *customer* query property to the given value. + /// + /// + /// Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. + pub fn customer(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._customer = Some(new_value.to_string()); + self + } + /// Sets the *custom field mask* query property to the given value. + /// + /// + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + pub fn custom_field_mask(mut self, new_value: &str) -> UserWatchCall<'a, C, NC, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete user +/// +/// A builder for the *delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().delete("userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserDeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a photo for the user +/// +/// A builder for the *photos.update* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::UserPhoto; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserPhoto = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().photos_update(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserPhotoUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: UserPhoto, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserPhotoUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserPhotoUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserPhoto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.photos.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserPhoto) -> UserPhotoUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserPhotoUpdateCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserPhotoUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserPhotoUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// retrieve user +/// +/// A builder for the *get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().get("userKey") +/// .view_type("vero") +/// .projection("diam") +/// .custom_field_mask("rebum.") +/// .doit(); +/// # } +/// ``` +pub struct UserGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _view_type: Option, + _projection: Option, + _custom_field_mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + if let Some(value) = self._view_type { + params.push(("viewType", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._custom_field_mask { + params.push(("customFieldMask", value.to_string())); + } + for &field in ["alt", "userKey", "viewType", "projection", "customFieldMask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *view type* query property to the given value. + /// + /// + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + pub fn view_type(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// What subset of fields to fetch for this user. + pub fn projection(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *custom field mask* query property to the given value. + /// + /// + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + pub fn custom_field_mask(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a alias for the user +/// +/// A builder for the *aliases.insert* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Alias; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Alias = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().aliases_insert(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Alias, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserAliaseInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserAliaseInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Alias)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.aliases.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Alias) -> UserAliaseInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserAliaseInsertCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserAliaseInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserAliaseInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve either deleted users or all users in a domain (paginated) +/// +/// A builder for the *list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().list() +/// .view_type("sadipscing") +/// .sort_order("vero") +/// .show_deleted("sadipscing") +/// .query("invidunt") +/// .projection("consetetur") +/// .page_token("dolore") +/// .order_by("duo") +/// .max_results(-82) +/// .event("Lorem") +/// .domain("et") +/// .customer("clita") +/// .custom_field_mask("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct UserListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _view_type: Option, + _sort_order: Option, + _show_deleted: Option, + _query: Option, + _projection: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _event: Option, + _domain: Option, + _customer: Option, + _custom_field_mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Users)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((14 + self._additional_params.len())); + if let Some(value) = self._view_type { + params.push(("viewType", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._event { + params.push(("event", value.to_string())); + } + if let Some(value) = self._domain { + params.push(("domain", value.to_string())); + } + if let Some(value) = self._customer { + params.push(("customer", value.to_string())); + } + if let Some(value) = self._custom_field_mask { + params.push(("customFieldMask", value.to_string())); + } + for &field in ["alt", "viewType", "sortOrder", "showDeleted", "query", "projection", "pageToken", "orderBy", "maxResults", "event", "domain", "customer", "customFieldMask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *view type* query property to the given value. + /// + /// + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + pub fn view_type(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Whether to return results in ascending or descending order. + pub fn sort_order(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// If set to true retrieves the list of deleted users. Default is false + pub fn show_deleted(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value.to_string()); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users + pub fn query(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// What subset of fields to fetch for this user. + pub fn projection(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Column to use for sorting results + pub fn order_by(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 100. Max allowed is 500 + pub fn max_results(mut self, new_value: i32) -> UserListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *event* query property to the given value. + /// + /// + /// Event on which subscription is intended (if subscribing) + pub fn event(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._event = Some(new_value.to_string()); + self + } + /// Sets the *domain* query property to the given value. + /// + /// + /// Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. + pub fn domain(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._domain = Some(new_value.to_string()); + self + } + /// Sets the *customer* query property to the given value. + /// + /// + /// Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. + pub fn customer(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._customer = Some(new_value.to_string()); + self + } + /// Sets the *custom field mask* query property to the given value. + /// + /// + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + pub fn custom_field_mask(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove a alias for the user +/// +/// A builder for the *aliases.delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().aliases_delete("userKey", "alias") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _alias: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserAliaseDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserAliaseDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.aliases.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("alias", self._alias.to_string())); + for &field in ["userKey", "alias"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/{alias}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{alias}", "alias")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "alias"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *alias* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The alias to be removed + pub fn alias(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, NC, A> { + self._alias = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserAliaseDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserAliaseDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// update user +/// +/// A builder for the *update* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: User = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().update(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &User) -> UserUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user. If Id, it should match with id of user object + pub fn user_key(mut self, new_value: &str) -> UserUpdateCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes in user aliases list +/// +/// A builder for the *aliases.watch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().aliases_watch(&req, "userKey") +/// .event("takimata") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Channel, + _user_key: String, + _event: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserAliaseWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserAliaseWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.aliases.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + if let Some(value) = self._event { + params.push(("event", value.to_string())); + } + for &field in ["alt", "userKey", "event"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> UserAliaseWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *event* query property to the given value. + /// + /// + /// Event on which subscription is intended (if subscribing) + pub fn event(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, NC, A> { + self._event = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserAliaseWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserAliaseWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all aliases for a user +/// +/// A builder for the *aliases.list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().aliases_list("userKey") +/// .event("labore") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _event: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserAliaseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserAliaseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Aliases)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.aliases.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + if let Some(value) = self._event { + params.push(("event", value.to_string())); + } + for &field in ["alt", "userKey", "event"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserAliaseListCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *event* query property to the given value. + /// + /// + /// Event on which subscription is intended (if subscribing) + pub fn event(mut self, new_value: &str) -> UserAliaseListCall<'a, C, NC, A> { + self._event = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserAliaseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserAliaseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve photo of a user +/// +/// A builder for the *photos.get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().photos_get("userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserPhotoGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserPhotoGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserPhotoGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserPhoto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.photos.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserPhotoGetCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserPhotoGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserPhotoGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a photo for the user. This method supports patch semantics. +/// +/// A builder for the *photos.patch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::UserPhoto; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserPhoto = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().photos_patch(&req, "userKey") +/// .doit(); +/// # } +/// ``` +pub struct UserPhotoPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: UserPhoto, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserPhotoPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserPhotoPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserPhoto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.users.photos.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserPhoto) -> UserPhotoPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> UserPhotoPatchCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserPhotoPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserPhotoPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete Mobile Device +/// +/// A builder for the *delete* method supported by a *mobiledevice* resource. +/// It is not used directly, but through a `MobiledeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mobiledevices().delete("customerId", "resourceId") +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _resource_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MobiledeviceDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobiledeviceDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.mobiledevices.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("resourceId", self._resource_id.to_string())); + for &field in ["customerId", "resourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{resourceId}", "resourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "resourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *resource id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Mobile Device + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, NC, A> { + self._resource_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobiledeviceDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobiledeviceDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve Mobile Device +/// +/// A builder for the *get* method supported by a *mobiledevice* resource. +/// It is not used directly, but through a `MobiledeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mobiledevices().get("customerId", "resourceId") +/// .projection("sed") +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _resource_id: String, + _projection: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MobiledeviceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobiledeviceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MobileDevice)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.mobiledevices.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("resourceId", self._resource_id.to_string())); + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + for &field in ["alt", "customerId", "resourceId", "projection"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{resourceId}", "resourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "resourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *resource id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Mobile Device + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, NC, A> { + self._resource_id = new_value.to_string(); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobiledeviceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobiledeviceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all Mobile Devices of a customer (paginated) +/// +/// A builder for the *list* method supported by a *mobiledevice* resource. +/// It is not used directly, but through a `MobiledeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mobiledevices().list("customerId") +/// .sort_order("sit") +/// .query("eirmod") +/// .projection("consetetur") +/// .page_token("labore") +/// .order_by("sed") +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _sort_order: Option, + _query: Option, + _projection: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MobiledeviceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobiledeviceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MobileDevices)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.mobiledevices.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "customerId", "sortOrder", "query", "projection", "pageToken", "orderBy", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Whether to return results in ascending or descending order. Only of use when orderBy is also used + pub fn sort_order(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search + pub fn query(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Column to use for sorting results + pub fn order_by(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 100 + pub fn max_results(mut self, new_value: i32) -> MobiledeviceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobiledeviceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobiledeviceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Take action on Mobile Device +/// +/// A builder for the *action* method supported by a *mobiledevice* resource. +/// It is not used directly, but through a `MobiledeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::MobileDeviceAction; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: MobileDeviceAction = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mobiledevices().action(&req, "customerId", "resourceId") +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceActionCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: MobileDeviceAction, + _customer_id: String, + _resource_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MobiledeviceActionCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobiledeviceActionCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.mobiledevices.action", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("resourceId", self._resource_id.to_string())); + for &field in ["customerId", "resourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}/action".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{resourceId}", "resourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "resourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &MobileDeviceAction) -> MobiledeviceActionCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceActionCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *resource id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Mobile Device + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceActionCall<'a, C, NC, A> { + self._resource_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceActionCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobiledeviceActionCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobiledeviceActionCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update membership of a user in the specified group. +/// +/// A builder for the *update* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Member; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Member = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().update(&req, "groupKey", "memberKey") +/// .doit(); +/// # } +/// ``` +pub struct MemberUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Member, + _group_key: String, + _member_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + params.push(("memberKey", self._member_key.to_string())); + for &field in ["alt", "groupKey", "memberKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupKey", "memberKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Member) -> MemberUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group. If Id, it should match with id of group object + pub fn group_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *member key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user. If Id, it should match with id of member object + pub fn member_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, NC, A> { + self._member_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve Group Member +/// +/// A builder for the *get* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().get("groupKey", "memberKey") +/// .doit(); +/// # } +/// ``` +pub struct MemberGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _member_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + params.push(("memberKey", self._member_key.to_string())); + for &field in ["alt", "groupKey", "memberKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupKey", "memberKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> MemberGetCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *member key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the member + pub fn member_key(mut self, new_value: &str) -> MemberGetCall<'a, C, NC, A> { + self._member_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add user to the specified group. +/// +/// A builder for the *insert* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Member; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Member = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().insert(&req, "groupKey") +/// .doit(); +/// # } +/// ``` +pub struct MemberInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Member, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Member) -> MemberInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> MemberInsertCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update membership of a user in the specified group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Member; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Member = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().patch(&req, "groupKey", "memberKey") +/// .doit(); +/// # } +/// ``` +pub struct MemberPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Member, + _group_key: String, + _member_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + params.push(("memberKey", self._member_key.to_string())); + for &field in ["alt", "groupKey", "memberKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupKey", "memberKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Member) -> MemberPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group. If Id, it should match with id of group object + pub fn group_key(mut self, new_value: &str) -> MemberPatchCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *member key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user. If Id, it should match with id of member object + pub fn member_key(mut self, new_value: &str) -> MemberPatchCall<'a, C, NC, A> { + self._member_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove membership. +/// +/// A builder for the *delete* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().delete("groupKey", "memberKey") +/// .doit(); +/// # } +/// ``` +pub struct MemberDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _member_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + params.push(("memberKey", self._member_key.to_string())); + for &field in ["groupKey", "memberKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupKey", "memberKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *member key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the member + pub fn member_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, NC, A> { + self._member_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all members in a group (paginated) +/// +/// A builder for the *list* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.members().list("groupKey") +/// .roles("justo") +/// .page_token("est") +/// .max_results(-46) +/// .doit(); +/// # } +/// ``` +pub struct MemberListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _roles: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MemberListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MemberListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Members)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.members.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + if let Some(value) = self._roles { + params.push(("roles", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "groupKey", "roles", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> MemberListCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *roles* query property to the given value. + /// + /// + /// Comma separated role values to filter list results on. + pub fn roles(mut self, new_value: &str) -> MemberListCall<'a, C, NC, A> { + self._roles = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> MemberListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 200 + pub fn max_results(mut self, new_value: i32) -> MemberListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MemberListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MemberListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of notifications. +/// +/// A builder for the *list* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.notifications().list("customer") +/// .page_token("clita") +/// .max_results(22) +/// .language("justo") +/// .doit(); +/// # } +/// ``` +pub struct NotificationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _page_token: Option, + _max_results: Option, + _language: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NotificationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Notifications)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.notifications.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._language { + params.push(("language", value.to_string())); + } + for &field in ["alt", "customer", "pageToken", "maxResults", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customer"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID for the customer's Google account. + pub fn customer(mut self, new_value: &str) -> NotificationListCall<'a, C, NC, A> { + self._customer = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token to specify the page of results to retrieve. + pub fn page_token(mut self, new_value: &str) -> NotificationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of notifications to return per page. The default is 100. + pub fn max_results(mut self, new_value: u32) -> NotificationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *language* query property to the given value. + /// + /// + /// The ISO 639-1 code of the language notifications are returned in. The default is English (en). + pub fn language(mut self, new_value: &str) -> NotificationListCall<'a, C, NC, A> { + self._language = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NotificationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NotificationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a notification +/// +/// A builder for the *delete* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.notifications().delete("customer", "notificationId") +/// .doit(); +/// # } +/// ``` +pub struct NotificationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _notification_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NotificationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.notifications.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + params.push(("notificationId", self._notification_id.to_string())); + for &field in ["customer", "notificationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{notificationId}", "notificationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customer", "notificationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. + pub fn customer(mut self, new_value: &str) -> NotificationDeleteCall<'a, C, NC, A> { + self._customer = new_value.to_string(); + self + } + /// Sets the *notification id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the notification. + pub fn notification_id(mut self, new_value: &str) -> NotificationDeleteCall<'a, C, NC, A> { + self._notification_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NotificationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NotificationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a notification. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Notification; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Notification = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.notifications().patch(&req, "customer", "notificationId") +/// .doit(); +/// # } +/// ``` +pub struct NotificationPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Notification, + _customer: String, + _notification_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NotificationPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Notification)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.notifications.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + params.push(("notificationId", self._notification_id.to_string())); + for &field in ["alt", "customer", "notificationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{notificationId}", "notificationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customer", "notificationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Notification) -> NotificationPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID for the customer's Google account. + pub fn customer(mut self, new_value: &str) -> NotificationPatchCall<'a, C, NC, A> { + self._customer = new_value.to_string(); + self + } + /// Sets the *notification id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the notification. + pub fn notification_id(mut self, new_value: &str) -> NotificationPatchCall<'a, C, NC, A> { + self._notification_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NotificationPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NotificationPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a notification. +/// +/// A builder for the *update* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Notification; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Notification = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.notifications().update(&req, "customer", "notificationId") +/// .doit(); +/// # } +/// ``` +pub struct NotificationUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Notification, + _customer: String, + _notification_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NotificationUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Notification)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.notifications.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + params.push(("notificationId", self._notification_id.to_string())); + for &field in ["alt", "customer", "notificationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{notificationId}", "notificationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customer", "notificationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Notification) -> NotificationUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID for the customer's Google account. + pub fn customer(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, NC, A> { + self._customer = new_value.to_string(); + self + } + /// Sets the *notification id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the notification. + pub fn notification_id(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, NC, A> { + self._notification_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NotificationUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NotificationUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a notification. +/// +/// A builder for the *get* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.notifications().get("customer", "notificationId") +/// .doit(); +/// # } +/// ``` +pub struct NotificationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _notification_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NotificationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NotificationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Notification)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.notifications.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + params.push(("notificationId", self._notification_id.to_string())); + for &field in ["alt", "customer", "notificationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{notificationId}", "notificationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customer", "notificationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. + pub fn customer(mut self, new_value: &str) -> NotificationGetCall<'a, C, NC, A> { + self._customer = new_value.to_string(); + self + } + /// Sets the *notification id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the notification. + pub fn notification_id(mut self, new_value: &str) -> NotificationGetCall<'a, C, NC, A> { + self._notification_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NotificationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NotificationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all Chrome OS Devices of a customer (paginated) +/// +/// A builder for the *list* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.chromeosdevices().list("customerId") +/// .sort_order("aliquyam") +/// .query("ea") +/// .projection("ea") +/// .page_token("et") +/// .order_by("dolor") +/// .max_results(-41) +/// .doit(); +/// # } +/// ``` +pub struct ChromeosdeviceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _sort_order: Option, + _query: Option, + _projection: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChromeosdeviceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChromeosdeviceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChromeOsDevices)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.chromeosdevices.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "customerId", "sortOrder", "query", "projection", "pageToken", "orderBy", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Whether to return results in ascending or descending order. Only of use when orderBy is also used + pub fn sort_order(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 + pub fn query(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Column to use for sorting results + pub fn order_by(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 100 + pub fn max_results(mut self, new_value: i32) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Chrome OS Device. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::ChromeOsDevice; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ChromeOsDevice = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.chromeosdevices().patch(&req, "customerId", "deviceId") +/// .projection("rebum.") +/// .doit(); +/// # } +/// ``` +pub struct ChromeosdevicePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: ChromeOsDevice, + _customer_id: String, + _device_id: String, + _projection: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChromeosdevicePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChromeosdevicePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChromeOsDevice)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.chromeosdevices.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + for &field in ["alt", "customerId", "deviceId", "projection"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ChromeOsDevice) -> ChromeosdevicePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Chrome OS Device + pub fn device_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdevicePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChromeosdevicePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChromeosdevicePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve Chrome OS Device +/// +/// A builder for the *get* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.chromeosdevices().get("customerId", "deviceId") +/// .projection("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct ChromeosdeviceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _device_id: String, + _projection: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChromeosdeviceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChromeosdeviceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChromeOsDevice)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.chromeosdevices.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + for &field in ["alt", "customerId", "deviceId", "projection"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Chrome OS Device + pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Chrome OS Device +/// +/// A builder for the *update* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::ChromeOsDevice; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ChromeOsDevice = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.chromeosdevices().update(&req, "customerId", "deviceId") +/// .projection("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct ChromeosdeviceUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: ChromeOsDevice, + _customer_id: String, + _device_id: String, + _projection: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChromeosdeviceUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChromeosdeviceUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChromeOsDevice)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.chromeosdevices.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + for &field in ["alt", "customerId", "deviceId", "projection"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ChromeOsDevice) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of Chrome OS Device + pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate new backup verification codes for the user. +/// +/// A builder for the *generate* method supported by a *verificationCode* resource. +/// It is not used directly, but through a `VerificationCodeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.verification_codes().generate("userKey") +/// .doit(); +/// # } +/// ``` +pub struct VerificationCodeGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VerificationCodeGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VerificationCodeGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.verificationCodes.generate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/generate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> VerificationCodeGenerateCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VerificationCodeGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VerificationCodeGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Invalidate the current backup verification codes for the user. +/// +/// A builder for the *invalidate* method supported by a *verificationCode* resource. +/// It is not used directly, but through a `VerificationCodeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.verification_codes().invalidate("userKey") +/// .doit(); +/// # } +/// ``` +pub struct VerificationCodeInvalidateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VerificationCodeInvalidateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VerificationCodeInvalidateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.verificationCodes.invalidate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/invalidate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the user + pub fn user_key(mut self, new_value: &str) -> VerificationCodeInvalidateCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeInvalidateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VerificationCodeInvalidateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VerificationCodeInvalidateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the current set of valid backup verification codes for the specified user. +/// +/// A builder for the *list* method supported by a *verificationCode* resource. +/// It is not used directly, but through a `VerificationCodeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.verification_codes().list("userKey") +/// .doit(); +/// # } +/// ``` +pub struct VerificationCodeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VerificationCodeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VerificationCodeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, VerificationCodes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.verificationCodes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> VerificationCodeListCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VerificationCodeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VerificationCodeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve Group +/// +/// A builder for the *get* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().get("groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Group)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> GroupGetCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all groups in a domain (paginated) +/// +/// A builder for the *list* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().list() +/// .user_key("elitr") +/// .page_token("nonumy") +/// .max_results(-15) +/// .domain("Lorem") +/// .customer("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct GroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: Option, + _page_token: Option, + _max_results: Option, + _domain: Option, + _customer: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Groups)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + if let Some(value) = self._user_key { + params.push(("userKey", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._domain { + params.push(("domain", value.to_string())); + } + if let Some(value) = self._customer { + params.push(("customer", value.to_string())); + } + for &field in ["alt", "userKey", "pageToken", "maxResults", "domain", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* query property to the given value. + /// + /// + /// Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object + pub fn user_key(mut self, new_value: &str) -> GroupListCall<'a, C, NC, A> { + self._user_key = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page in the list + pub fn page_token(mut self, new_value: &str) -> GroupListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Default is 200 + pub fn max_results(mut self, new_value: i32) -> GroupListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *domain* query property to the given value. + /// + /// + /// Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead. + pub fn domain(mut self, new_value: &str) -> GroupListCall<'a, C, NC, A> { + self._domain = Some(new_value.to_string()); + self + } + /// Sets the *customer* query property to the given value. + /// + /// + /// Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain. + pub fn customer(mut self, new_value: &str) -> GroupListCall<'a, C, NC, A> { + self._customer = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all aliases for a group +/// +/// A builder for the *aliases.list* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().aliases_list("groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupAliaseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupAliaseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupAliaseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Aliases)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.aliases.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> GroupAliaseListCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupAliaseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupAliaseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Group; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Group = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().patch(&req, "groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Group)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Group) -> GroupPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group. If Id, it should match with id of group object + pub fn group_key(mut self, new_value: &str) -> GroupPatchCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update Group +/// +/// A builder for the *update* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Group; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Group = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().update(&req, "groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Group)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Group) -> GroupUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group. If Id, it should match with id of group object + pub fn group_key(mut self, new_value: &str) -> GroupUpdateCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete Group +/// +/// A builder for the *delete* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().delete("groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> GroupDeleteCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a alias for the group +/// +/// A builder for the *aliases.insert* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Alias; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Alias = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().aliases_insert(&req, "groupKey") +/// .doit(); +/// # } +/// ``` +pub struct GroupAliaseInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Alias, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupAliaseInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupAliaseInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Alias)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.aliases.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + for &field in ["alt", "groupKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["groupKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Alias) -> GroupAliaseInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> GroupAliaseInsertCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupAliaseInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupAliaseInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove a alias for the group +/// +/// A builder for the *aliases.delete* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().aliases_delete("groupKey", "alias") +/// .doit(); +/// # } +/// ``` +pub struct GroupAliaseDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _alias: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupAliaseDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupAliaseDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.aliases.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("groupKey", self._group_key.to_string())); + params.push(("alias", self._alias.to_string())); + for &field in ["groupKey", "alias"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases/{alias}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{alias}", "alias")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupKey", "alias"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *group key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Email or immutable Id of the group + pub fn group_key(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, NC, A> { + self._group_key = new_value.to_string(); + self + } + /// Sets the *alias* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The alias to be removed + pub fn alias(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, NC, A> { + self._alias = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupAliaseDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupAliaseDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create Group +/// +/// A builder for the *insert* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Group; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Group = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.groups().insert(&req) +/// .doit(); +/// # } +/// ``` +pub struct GroupInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GroupInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GroupInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Group)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.groups.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/groups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Group) -> GroupInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete an ASP issued by a user. +/// +/// A builder for the *delete* method supported by a *asp* resource. +/// It is not used directly, but through a `AspMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.asps().delete("userKey", -36) +/// .doit(); +/// # } +/// ``` +pub struct AspDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _code_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AspDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AspDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.asps.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("codeId", self._code_id.to_string())); + for &field in ["userKey", "codeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{codeId}", "codeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "codeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> AspDeleteCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *code id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the ASP to be deleted. + pub fn code_id(mut self, new_value: i32) -> AspDeleteCall<'a, C, NC, A> { + self._code_id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AspDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AspDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AspDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the ASPs issued by a user. +/// +/// A builder for the *list* method supported by a *asp* resource. +/// It is not used directly, but through a `AspMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.asps().list("userKey") +/// .doit(); +/// # } +/// ``` +pub struct AspListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AspListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AspListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Asps)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.asps.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["alt", "userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> AspListCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AspListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AspListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AspListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about an ASP issued by a user. +/// +/// A builder for the *get* method supported by a *asp* resource. +/// It is not used directly, but through a `AspMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.asps().get("userKey", -27) +/// .doit(); +/// # } +/// ``` +pub struct AspGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _code_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AspGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AspGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Asp)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.asps.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("codeId", self._code_id.to_string())); + for &field in ["alt", "userKey", "codeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{codeId}", "codeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "codeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + pub fn user_key(mut self, new_value: &str) -> AspGetCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *code id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The unique ID of the ASP. + pub fn code_id(mut self, new_value: i32) -> AspGetCall<'a, C, NC, A> { + self._code_id = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AspGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AspGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AspGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve all schemas for a customer +/// +/// A builder for the *list* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().list("customerId") +/// .doit(); +/// # } +/// ``` +pub struct SchemaListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schemas)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + for &field in ["alt", "customerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaListCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve schema +/// +/// A builder for the *get* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().get("customerId", "schemaKey") +/// .doit(); +/// # } +/// ``` +pub struct SchemaGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _schema_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schema)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("schemaKey", self._schema_key.to_string())); + for &field in ["alt", "customerId", "schemaKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{schemaKey}", "schemaKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "schemaKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaGetCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *schema key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name or immutable Id of the schema + pub fn schema_key(mut self, new_value: &str) -> SchemaGetCall<'a, C, NC, A> { + self._schema_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update schema. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Schema; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Schema = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().patch(&req, "customerId", "schemaKey") +/// .doit(); +/// # } +/// ``` +pub struct SchemaPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Schema, + _customer_id: String, + _schema_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schema)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("schemaKey", self._schema_key.to_string())); + for &field in ["alt", "customerId", "schemaKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{schemaKey}", "schemaKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "schemaKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Schema) -> SchemaPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaPatchCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *schema key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name or immutable Id of the schema. + pub fn schema_key(mut self, new_value: &str) -> SchemaPatchCall<'a, C, NC, A> { + self._schema_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create schema. +/// +/// A builder for the *insert* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Schema; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Schema = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().insert(&req, "customerId") +/// .doit(); +/// # } +/// ``` +pub struct SchemaInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Schema, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schema)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + for &field in ["alt", "customerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Schema) -> SchemaInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaInsertCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete schema +/// +/// A builder for the *delete* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().delete("customerId", "schemaKey") +/// .doit(); +/// # } +/// ``` +pub struct SchemaDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _schema_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("schemaKey", self._schema_key.to_string())); + for &field in ["customerId", "schemaKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{schemaKey}", "schemaKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "schemaKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *schema key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name or immutable Id of the schema + pub fn schema_key(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, NC, A> { + self._schema_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update schema +/// +/// A builder for the *update* method supported by a *schema* resource. +/// It is not used directly, but through a `SchemaMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_directory" as admin1_directory; +/// use admin1_directory::Schema; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_directory::Directory; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Directory::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Schema = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schemas().update(&req, "customerId", "schemaKey") +/// .doit(); +/// # } +/// ``` +pub struct SchemaUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Directory, + _request: Schema, + _customer_id: String, + _schema_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchemaUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchemaUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schema)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "directory.schemas.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("schemaKey", self._schema_key.to_string())); + for &field in ["alt", "customerId", "schemaKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{schemaKey}", "schemaKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "schemaKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Schema) -> SchemaUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Immutable id of the Google Apps account + pub fn customer_id(mut self, new_value: &str) -> SchemaUpdateCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *schema key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name or immutable Id of the schema. + pub fn schema_key(mut self, new_value: &str) -> SchemaUpdateCall<'a, C, NC, A> { + self._schema_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchemaUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchemaUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/admin1_reports/Cargo.toml b/gen/admin1_reports/Cargo.toml new file mode 100644 index 0000000000..407f828c83 --- /dev/null +++ b/gen/admin1_reports/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-admin1_reports" +version = "0.1.0+20150115" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with reports (protocol reports_v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/admin1_reports" +homepage = "https://developers.google.com/admin-sdk/reports/" +documentation = "http://byron.github.io/google-apis-rs/google-admin1_reports" +license = "MIT" +keywords = ["admin", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/admin1_reports/LICENSE.md b/gen/admin1_reports/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/admin1_reports/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/admin1_reports/README.md b/gen/admin1_reports/README.md new file mode 100644 index 0000000000..1cb5ea810b --- /dev/null +++ b/gen/admin1_reports/README.md @@ -0,0 +1,189 @@ + +The `google-admin1_reports` library allows access to all features of the *Google reports* service. + +This documentation was generated from *reports* crate version *0.1.0+20150115*, where *20150115* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *reports* *v1_reports* API can be found at the +[official documentation site](https://developers.google.com/admin-sdk/reports/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.Reports.html) ... + +* [activities](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.Activity.html) + * [*list*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.ActivityListCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.ActivityWatchCall.html) +* [channels](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.Channel.html) + * [*stop*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.ChannelStopCall.html) +* customer usage reports + * [*get*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.CustomerUsageReportGetCall.html) +* user usage report + * [*get*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.UserUsageReportGetCall.html) + + +Subscription supported by ... + +* [*watch activities*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.ActivityWatchCall.html) +* [*list activities*](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.ActivityListCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-admin1_reports/struct.Reports.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.activities().watch(...).doit() +let r = hub.channels().stop(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-admin1_reports = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-admin1_reports" as admin1_reports; +use admin1_reports::Channel; +use admin1_reports::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use admin1_reports::Reports; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Reports::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Channel = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.activities().watch(&req, "userKey", "applicationName") + .start_time("Stet") + .page_token("sed") + .max_results(-85) + .filters("dolores") + .event_name("kasd") + .end_time("accusam") + .customer_id("takimata") + .actor_ip_address("justo") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-admin1_reports/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-admin1_reports/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-admin1_reports/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-admin1_reports/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **admin1_reports** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/admin1_reports/src/cmn.rs b/gen/admin1_reports/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/admin1_reports/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/admin1_reports/src/lib.rs b/gen/admin1_reports/src/lib.rs new file mode 100644 index 0000000000..22407c45b6 --- /dev/null +++ b/gen/admin1_reports/src/lib.rs @@ -0,0 +1,2466 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *reports* crate version *0.1.0+20150115*, where *20150115* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *reports* *v1_reports* API can be found at the +//! [official documentation site](https://developers.google.com/admin-sdk/reports/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/admin1_reports). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Reports.html) ... +//! +//! * [activities](struct.Activity.html) +//! * [*list*](struct.ActivityListCall.html) and [*watch*](struct.ActivityWatchCall.html) +//! * [channels](struct.Channel.html) +//! * [*stop*](struct.ChannelStopCall.html) +//! * customer usage reports +//! * [*get*](struct.CustomerUsageReportGetCall.html) +//! * user usage report +//! * [*get*](struct.UserUsageReportGetCall.html) +//! +//! +//! Subscription supported by ... +//! +//! * [*watch activities*](struct.ActivityWatchCall.html) +//! * [*list activities*](struct.ActivityListCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Reports.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.activities().watch(...).doit() +//! let r = hub.channels().stop(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-admin1_reports = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-admin1_reports" as admin1_reports; +//! use admin1_reports::Channel; +//! use admin1_reports::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use admin1_reports::Reports; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Reports::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Channel = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.activities().watch(&req, "userKey", "applicationName") +//! .start_time("labore") +//! .page_token("sea") +//! .max_results(-90) +//! .filters("dolores") +//! .event_name("gubergren") +//! .end_time("sadipscing") +//! .customer_id("aliquyam") +//! .actor_ip_address("ea") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View audit reports of Google Apps for your domain + ReportAuditReadonly, + + /// View usage reports of Google Apps for your domain + ReportUsageReadonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::ReportAuditReadonly => "https://www.googleapis.com/auth/admin.reports.audit.readonly", + Scope::ReportUsageReadonly => "https://www.googleapis.com/auth/admin.reports.usage.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::ReportAuditReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Reports related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_reports" as admin1_reports; +/// use admin1_reports::Channel; +/// use admin1_reports::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_reports::Reports; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Reports::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().watch(&req, "userKey", "applicationName") +/// .start_time("justo") +/// .page_token("et") +/// .max_results(-17) +/// .filters("diam") +/// .event_name("ipsum") +/// .end_time("Lorem") +/// .customer_id("et") +/// .actor_ip_address("duo") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Reports { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Reports {} + +impl<'a, C, NC, A> Reports + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Reports { + Reports { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn activities(&'a self) -> ActivityMethods<'a, C, NC, A> { + ActivityMethods { hub: &self } + } + pub fn channels(&'a self) -> ChannelMethods<'a, C, NC, A> { + ChannelMethods { hub: &self } + } + pub fn customer_usage_reports(&'a self) -> CustomerUsageReportMethods<'a, C, NC, A> { + CustomerUsageReportMethods { hub: &self } + } + pub fn user_usage_report(&'a self) -> UserUsageReportMethods<'a, C, NC, A> { + UserUsageReportMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// JSON template for a collection of activites. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list activities](struct.ActivityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Activities { + /// Token for retrieving the next page + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Each record in read response. + pub items: Vec, + /// Kind of list response this is. + pub kind: String, + /// ETag of the resource. + pub etag: String, +} + +impl ResponseResult for Activities {} + + +/// Key-Value pairs to give detailed information on the warning. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReportsWarningsData { + /// Key associated with a key-value pair to give detailed information on the warning. + pub key: String, + /// Value associated with a key-value pair to give detailed information on the warning. + pub value: String, +} + +impl NestedType for UsageReportsWarningsData {} +impl Part for UsageReportsWarningsData {} + + +/// JSON template for a usage report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReport { + /// The date to which the record belongs. + pub date: String, + /// The kind of object. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// Parameter value pairs for various applications. + pub parameters: Vec, + /// Information about the type of the item. + pub entity: UsageReportEntity, +} + +impl Part for UsageReport {} + + +/// Parameter value pairs for various applications. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReportParameters { + /// Nested message value of the parameter. + #[serde(alias="msgValue")] + pub msg_value: Vec>, + /// RFC 3339 formatted value of the parameter. + #[serde(alias="datetimeValue")] + pub datetime_value: String, + /// The name of the parameter. + pub name: String, + /// String value of the parameter. + #[serde(alias="stringValue")] + pub string_value: String, + /// Boolean value of the parameter. + #[serde(alias="boolValue")] + pub bool_value: bool, + /// Integral value of the parameter. + #[serde(alias="intValue")] + pub int_value: String, +} + +impl NestedType for UsageReportParameters {} +impl Part for UsageReportParameters {} + + +/// User doing the action. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityActor { + /// Obfuscated user id of the user. + #[serde(alias="profileId")] + pub profile_id: String, + /// Email address of the user. + pub email: String, + /// For OAuth 2LO API requests, consumer_key of the requestor. + pub key: String, + /// User or OAuth 2LO request. + #[serde(alias="callerType")] + pub caller_type: String, +} + +impl NestedType for ActivityActor {} +impl Part for ActivityActor {} + + +/// Unique identifier for each activity record. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityId { + /// Application name to which the event belongs. + #[serde(alias="applicationName")] + pub application_name: String, + /// Unique qualifier if multiple events have the same time. + #[serde(alias="uniqueQualifier")] + pub unique_qualifier: String, + /// Obfuscated customer ID of the source customer. + #[serde(alias="customerId")] + pub customer_id: String, + /// Time of occurrence of the activity. + pub time: String, +} + +impl NestedType for ActivityId {} +impl Part for ActivityId {} + + +/// Warnings if any. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReportsWarnings { + /// Human readable message for the warning. + pub message: String, + /// Machine readable code / warning type. + pub code: String, + /// Key-Value pairs to give detailed information on the warning. + pub data: Vec, +} + +impl NestedType for UsageReportsWarnings {} +impl Part for UsageReportsWarnings {} + + +/// JSON template for a collection of usage reports. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get user usage report](struct.UserUsageReportGetCall.html) (response) +/// * [get customer usage reports](struct.CustomerUsageReportGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReports { + /// Token for retrieving the next page + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The kind of object. + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// Various application parameter records. + #[serde(alias="usageReports")] + pub usage_reports: Vec, + /// Warnings if any. + pub warnings: Vec, +} + +impl ResponseResult for UsageReports {} + + +/// JSON template for the activity resource. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Activity { + /// Kind of resource this is. + pub kind: String, + /// ETag of the entry. + pub etag: String, + /// Activity events. + pub events: Vec, + /// IP Address of the user doing the action. + #[serde(alias="ipAddress")] + pub ip_address: String, + /// Domain of source customer. + #[serde(alias="ownerDomain")] + pub owner_domain: String, + /// User doing the action. + pub actor: ActivityActor, + /// Unique identifier for each activity record. + pub id: ActivityId, +} + +impl Part for Activity {} + + +/// Parameter value pairs for various applications. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityEventsParameters { + /// Boolean value of the parameter. + #[serde(alias="boolValue")] + pub bool_value: bool, + /// Multi-string value of the parameter. + #[serde(alias="multiValue")] + pub multi_value: Vec, + /// The name of the parameter. + pub name: String, + /// Multi-int value of the parameter. + #[serde(alias="multiIntValue")] + pub multi_int_value: Vec, + /// Integral value of the parameter. + #[serde(alias="intValue")] + pub int_value: String, + /// String value of the parameter. + pub value: String, +} + +impl NestedType for ActivityEventsParameters {} +impl Part for ActivityEventsParameters {} + + +/// Activity events. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityEvents { + /// Type of event. + #[serde(alias="type")] + pub type_: String, + /// Name of event. + pub name: String, + /// Parameter value pairs for various applications. + pub parameters: Vec, +} + +impl NestedType for ActivityEvents {} +impl Part for ActivityEvents {} + + +/// Information about the type of the item. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsageReportEntity { + /// Obfuscated user id for the record. + #[serde(alias="profileId")] + pub profile_id: String, + /// user's email. + #[serde(alias="userEmail")] + pub user_email: String, + /// The type of item, can be a customer or user. + #[serde(alias="type")] + pub type_: String, + /// Obfuscated customer id for the record. + #[serde(alias="customerId")] + pub customer_id: String, +} + +impl NestedType for UsageReportEntity {} +impl Part for UsageReportEntity {} + + +/// An notification channel used to watch for resource changes. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [watch activities](struct.ActivityWatchCall.html) (request|response) +/// * [stop channels](struct.ChannelStopCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Channel { + /// A version-specific identifier for the watched resource. + #[serde(alias="resourceUri")] + pub resource_uri: Option, + /// Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". + pub kind: Option, + /// An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. + #[serde(alias="resourceId")] + pub resource_id: Option, + /// A UUID or similar unique string that identifies this channel. + pub id: Option, + /// An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. + pub token: Option, + /// Additional parameters controlling delivery channel behavior. Optional. + pub params: Option>, + /// Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. + pub expiration: Option, + /// The address where notifications are delivered for this channel. + pub address: Option, + /// The type of delivery mechanism used for this channel. + #[serde(alias="type")] + pub type_: Option, + /// A Boolean value to indicate whether payload is wanted. Optional. + pub payload: Option, +} + +impl RequestValue for Channel {} +impl Resource for Channel {} +impl ResponseResult for Channel {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *channel* resources. +/// It is not used directly, but through the `Reports` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_reports" as admin1_reports; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_reports::Reports; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Reports::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `stop(...)` +/// // to build up your call. +/// let rb = hub.channels(); +/// # } +/// ``` +pub struct ChannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Stop watching resources through this channel + pub fn stop(&self, request: &Channel) -> ChannelStopCall<'a, C, NC, A> { + ChannelStopCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *activity* resources. +/// It is not used directly, but through the `Reports` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_reports" as admin1_reports; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_reports::Reports; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Reports::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.activities(); +/// # } +/// ``` +pub struct ActivityMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ActivityMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Push changes to activities + pub fn watch(&self, request: &Channel, user_key: &str, application_name: &str) -> ActivityWatchCall<'a, C, NC, A> { + ActivityWatchCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _application_name: application_name.to_string(), + _start_time: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _event_name: Default::default(), + _end_time: Default::default(), + _customer_id: Default::default(), + _actor_ip_address: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of activities for a specific customer and application. + pub fn list(&self, user_key: &str, application_name: &str) -> ActivityListCall<'a, C, NC, A> { + ActivityListCall { + hub: self.hub, + _user_key: user_key.to_string(), + _application_name: application_name.to_string(), + _start_time: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _event_name: Default::default(), + _end_time: Default::default(), + _customer_id: Default::default(), + _actor_ip_address: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *customerUsageReport* resources. +/// It is not used directly, but through the `Reports` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_reports" as admin1_reports; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_reports::Reports; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Reports::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.customer_usage_reports(); +/// # } +/// ``` +pub struct CustomerUsageReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CustomerUsageReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomerUsageReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a report which is a collection of properties / statistics for a specific customer. + pub fn get(&self, date: &str) -> CustomerUsageReportGetCall<'a, C, NC, A> { + CustomerUsageReportGetCall { + hub: self.hub, + _date: date.to_string(), + _parameters: Default::default(), + _page_token: Default::default(), + _customer_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *userUsageReport* resources. +/// It is not used directly, but through the `Reports` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin1_reports" as admin1_reports; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin1_reports::Reports; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Reports::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.user_usage_report(); +/// # } +/// ``` +pub struct UserUsageReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserUsageReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserUsageReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a report which is a collection of properties / statistics for a set of users. + pub fn get(&self, user_key: &str, date: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + UserUsageReportGetCall { + hub: self.hub, + _user_key: user_key.to_string(), + _date: date.to_string(), + _parameters: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _customer_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Stop watching resources through this channel +/// +/// A builder for the *stop* method supported by a *channel* resource. +/// It is not used directly, but through a `ChannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_reports" as admin1_reports; +/// use admin1_reports::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_reports::Reports; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Reports::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.channels().stop(&req) +/// .doit(); +/// # } +/// ``` +pub struct ChannelStopCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, + _request: Channel, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChannelStopCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelStopCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "admin.channels.stop", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in [].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/admin/reports/v1//admin/reports_v1/channels/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ReportAuditReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ChannelStopCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Push changes to activities +/// +/// A builder for the *watch* method supported by a *activity* resource. +/// It is not used directly, but through a `ActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_reports" as admin1_reports; +/// use admin1_reports::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_reports::Reports; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Reports::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().watch(&req, "userKey", "applicationName") +/// .start_time("Lorem") +/// .page_token("eos") +/// .max_results(-81) +/// .filters("sadipscing") +/// .event_name("dolor") +/// .end_time("eirmod") +/// .customer_id("elitr") +/// .actor_ip_address("amet") +/// .doit(); +/// # } +/// ``` +pub struct ActivityWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, + _request: Channel, + _user_key: String, + _application_name: String, + _start_time: Option, + _page_token: Option, + _max_results: Option, + _filters: Option, + _event_name: Option, + _end_time: Option, + _customer_id: Option, + _actor_ip_address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ActivityWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "reports.activities.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("applicationName", self._application_name.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._event_name { + params.push(("eventName", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + if let Some(value) = self._customer_id { + params.push(("customerId", value.to_string())); + } + if let Some(value) = self._actor_ip_address { + params.push(("actorIpAddress", value.to_string())); + } + for &field in ["alt", "userKey", "applicationName", "startTime", "pageToken", "maxResults", "filters", "eventName", "endTime", "customerId", "actorIpAddress"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/reports/v1/activity/users/{userKey}/applications/{applicationName}/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ReportAuditReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{applicationName}", "applicationName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "applicationName"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ActivityWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the profile id or the user email for which the data should be filtered. When 'all' is specified as the userKey, it returns usageReports for all users. + pub fn user_key(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *application name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Application name for which the events are to be retrieved. + pub fn application_name(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._application_name = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// Return events which occured at or after this time. + pub fn start_time(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page. + pub fn page_token(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Number of activity records to be shown in each page. + pub fn max_results(mut self, new_value: i32) -> ActivityWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2 name][operator][parameter2 value],... + pub fn filters(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *event name* query property to the given value. + /// + /// + /// Name of the event being queried. + pub fn event_name(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._event_name = Some(new_value.to_string()); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// Return events which occured at or before this time. + pub fn end_time(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *customer id* query property to the given value. + /// + /// + /// Represents the customer for which the data is to be fetched. + pub fn customer_id(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._customer_id = Some(new_value.to_string()); + self + } + /// Sets the *actor ip address* query property to the given value. + /// + /// + /// IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses. + pub fn actor_ip_address(mut self, new_value: &str) -> ActivityWatchCall<'a, C, NC, A> { + self._actor_ip_address = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ActivityWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ActivityWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ActivityWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of activities for a specific customer and application. +/// +/// A builder for the *list* method supported by a *activity* resource. +/// It is not used directly, but through a `ActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_reports" as admin1_reports; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_reports::Reports; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Reports::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().list("userKey", "applicationName") +/// .start_time("eirmod") +/// .page_token("dolore") +/// .max_results(-37) +/// .filters("aliquyam") +/// .event_name("accusam") +/// .end_time("Lorem") +/// .customer_id("sea") +/// .actor_ip_address("et") +/// .doit(); +/// # } +/// ``` +pub struct ActivityListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, + _user_key: String, + _application_name: String, + _start_time: Option, + _page_token: Option, + _max_results: Option, + _filters: Option, + _event_name: Option, + _end_time: Option, + _customer_id: Option, + _actor_ip_address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ActivityListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Activities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "reports.activities.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("applicationName", self._application_name.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._event_name { + params.push(("eventName", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + if let Some(value) = self._customer_id { + params.push(("customerId", value.to_string())); + } + if let Some(value) = self._actor_ip_address { + params.push(("actorIpAddress", value.to_string())); + } + for &field in ["alt", "userKey", "applicationName", "startTime", "pageToken", "maxResults", "filters", "eventName", "endTime", "customerId", "actorIpAddress"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/reports/v1/activity/users/{userKey}/applications/{applicationName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ReportAuditReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{applicationName}", "applicationName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "applicationName"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the profile id or the user email for which the data should be filtered. When 'all' is specified as the userKey, it returns usageReports for all users. + pub fn user_key(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *application name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Application name for which the events are to be retrieved. + pub fn application_name(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._application_name = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// Return events which occured at or after this time. + pub fn start_time(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page. + pub fn page_token(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Number of activity records to be shown in each page. + pub fn max_results(mut self, new_value: i32) -> ActivityListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2 name][operator][parameter2 value],... + pub fn filters(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *event name* query property to the given value. + /// + /// + /// Name of the event being queried. + pub fn event_name(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._event_name = Some(new_value.to_string()); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// Return events which occured at or before this time. + pub fn end_time(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *customer id* query property to the given value. + /// + /// + /// Represents the customer for which the data is to be fetched. + pub fn customer_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._customer_id = Some(new_value.to_string()); + self + } + /// Sets the *actor ip address* query property to the given value. + /// + /// + /// IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses. + pub fn actor_ip_address(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._actor_ip_address = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ActivityListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ActivityListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ActivityListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a report which is a collection of properties / statistics for a specific customer. +/// +/// A builder for the *get* method supported by a *customerUsageReport* resource. +/// It is not used directly, but through a `CustomerUsageReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_reports" as admin1_reports; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_reports::Reports; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Reports::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customer_usage_reports().get("date") +/// .parameters("et") +/// .page_token("eirmod") +/// .customer_id("sanctus") +/// .doit(); +/// # } +/// ``` +pub struct CustomerUsageReportGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, + _date: String, + _parameters: Option, + _page_token: Option, + _customer_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomerUsageReportGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomerUsageReportGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UsageReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "reports.customerUsageReports.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("date", self._date.to_string())); + if let Some(value) = self._parameters { + params.push(("parameters", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._customer_id { + params.push(("customerId", value.to_string())); + } + for &field in ["alt", "date", "parameters", "pageToken", "customerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/reports/v1/usage/dates/{date}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ReportAuditReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{date}", "date")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["date"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *date* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the date in yyyy-mm-dd format for which the data is to be fetched. + pub fn date(mut self, new_value: &str) -> CustomerUsageReportGetCall<'a, C, NC, A> { + self._date = new_value.to_string(); + self + } + /// Sets the *parameters* query property to the given value. + /// + /// + /// Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2. + pub fn parameters(mut self, new_value: &str) -> CustomerUsageReportGetCall<'a, C, NC, A> { + self._parameters = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page. + pub fn page_token(mut self, new_value: &str) -> CustomerUsageReportGetCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *customer id* query property to the given value. + /// + /// + /// Represents the customer for which the data is to be fetched. + pub fn customer_id(mut self, new_value: &str) -> CustomerUsageReportGetCall<'a, C, NC, A> { + self._customer_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomerUsageReportGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomerUsageReportGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomerUsageReportGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a report which is a collection of properties / statistics for a set of users. +/// +/// A builder for the *get* method supported by a *userUsageReport* resource. +/// It is not used directly, but through a `UserUsageReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin1_reports" as admin1_reports; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin1_reports::Reports; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Reports::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_usage_report().get("userKey", "date") +/// .parameters("et") +/// .page_token("consetetur") +/// .max_results(65) +/// .filters("ea") +/// .customer_id("sed") +/// .doit(); +/// # } +/// ``` +pub struct UserUsageReportGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Reports, + _user_key: String, + _date: String, + _parameters: Option, + _page_token: Option, + _max_results: Option, + _filters: Option, + _customer_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserUsageReportGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserUsageReportGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UsageReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "reports.userUsageReport.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + params.push(("date", self._date.to_string())); + if let Some(value) = self._parameters { + params.push(("parameters", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._customer_id { + params.push(("customerId", value.to_string())); + } + for &field in ["alt", "userKey", "date", "parameters", "pageToken", "maxResults", "filters", "customerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/admin/reports/v1/usage/users/{userKey}/dates/{date}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ReportAuditReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey"), ("{date}", "date")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userKey", "date"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the profile id or the user email for which the data should be filtered. + pub fn user_key(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *date* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the date in yyyy-mm-dd format for which the data is to be fetched. + pub fn date(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._date = new_value.to_string(); + self + } + /// Sets the *parameters* query property to the given value. + /// + /// + /// Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2. + pub fn parameters(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._parameters = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token to specify next page. + pub fn page_token(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. Maximum allowed is 1000 + pub fn max_results(mut self, new_value: u32) -> UserUsageReportGetCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// Represents the set of filters including parameter operator value. + pub fn filters(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *customer id* query property to the given value. + /// + /// + /// Represents the customer for which the data is to be fetched. + pub fn customer_id(mut self, new_value: &str) -> UserUsageReportGetCall<'a, C, NC, A> { + self._customer_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUsageReportGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserUsageReportGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserUsageReportGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/admin2_email_migration/Cargo.toml b/gen/admin2_email_migration/Cargo.toml new file mode 100644 index 0000000000..9f8bfd406f --- /dev/null +++ b/gen/admin2_email_migration/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-admin2_email_migration" +version = "0.1.0+20150303" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with admin (protocol email_migration_v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/admin2_email_migration" +homepage = "https://developers.google.com/admin-sdk/email-migration/v2/" +documentation = "http://byron.github.io/google-apis-rs/google-admin2_email_migration" +license = "MIT" +keywords = ["admin", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/admin2_email_migration/LICENSE.md b/gen/admin2_email_migration/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/admin2_email_migration/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/admin2_email_migration/README.md b/gen/admin2_email_migration/README.md new file mode 100644 index 0000000000..37010c90d8 --- /dev/null +++ b/gen/admin2_email_migration/README.md @@ -0,0 +1,174 @@ + +The `google-admin2_email_migration` library allows access to all features of the *Google admin* service. + +This documentation was generated from *admin* crate version *0.1.0+20150303*, where *20150303* is the exact revision of the *admin:email_migration_v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *admin* *v2_email_migration* API can be found at the +[official documentation site](https://developers.google.com/admin-sdk/email-migration/v2/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-admin2_email_migration/struct.Admin.html) ... + +* mail + * [*insert*](http://byron.github.io/google-apis-rs/google-admin2_email_migration/struct.MailInsertCall.html) + + +Upload supported by ... + +* [*insert mail*](http://byron.github.io/google-apis-rs/google-admin2_email_migration/struct.MailInsertCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-admin2_email_migration/struct.Admin.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.mail().insert(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-admin2_email_migration = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-admin2_email_migration" as admin2_email_migration; +use admin2_email_migration::MailItem; +use admin2_email_migration::Result; +use std::fs; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use admin2_email_migration::Admin; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Admin::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: MailItem = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `upload(...)`. +// Values shown here are possibly random and not representative ! +let result = hub.mail().insert(&req, "userKey") + .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-admin2_email_migration/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-admin2_email_migration/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-admin2_email_migration/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-admin2_email_migration/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **admin2_email_migration** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/admin2_email_migration/src/cmn.rs b/gen/admin2_email_migration/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/admin2_email_migration/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/admin2_email_migration/src/lib.rs b/gen/admin2_email_migration/src/lib.rs new file mode 100644 index 0000000000..eb6b44573d --- /dev/null +++ b/gen/admin2_email_migration/src/lib.rs @@ -0,0 +1,795 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *admin* crate version *0.1.0+20150303*, where *20150303* is the exact revision of the *admin:email_migration_v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *admin* *v2_email_migration* API can be found at the +//! [official documentation site](https://developers.google.com/admin-sdk/email-migration/v2/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/admin2_email_migration). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Admin.html) ... +//! +//! * mail +//! * [*insert*](struct.MailInsertCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*insert mail*](struct.MailInsertCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Admin.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.mail().insert(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-admin2_email_migration = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-admin2_email_migration" as admin2_email_migration; +//! use admin2_email_migration::MailItem; +//! use admin2_email_migration::Result; +//! use std::fs; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use admin2_email_migration::Admin; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Admin::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: MailItem = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `upload(...)`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.mail().insert(&req, "userKey") +//! .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage email messages of users on your domain + EmailMigration, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::EmailMigration => "https://www.googleapis.com/auth/email.migration", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::EmailMigration + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Admin related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin2_email_migration" as admin2_email_migration; +/// use admin2_email_migration::MailItem; +/// use admin2_email_migration::Result; +/// use std::fs; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin2_email_migration::Admin; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Admin::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: MailItem = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mail().insert(&req, "userKey") +/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Admin { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Admin {} + +impl<'a, C, NC, A> Admin + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Admin { + Admin { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn mail(&'a self) -> MailMethods<'a, C, NC, A> { + MailMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// JSON template for MailItem object in Email Migration API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert mail](struct.MailInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct MailItem { + /// Boolean indicating if the mail is in trash + #[serde(alias="isTrash")] + pub is_trash: Option, + /// Kind of resource this is. + pub kind: Option, + /// List of labels (strings) + pub labels: Option>, + /// Boolean indicating if the mail is draft + #[serde(alias="isDraft")] + pub is_draft: Option, + /// Boolean indicating if the mail is in inbox + #[serde(alias="isInbox")] + pub is_inbox: Option, + /// Boolean indicating if the mail is in 'sent mails' + #[serde(alias="isSent")] + pub is_sent: Option, + /// Boolean indicating if the mail is starred + #[serde(alias="isStarred")] + pub is_starred: Option, + /// Boolean indicating if the mail is unread + #[serde(alias="isUnread")] + pub is_unread: Option, + /// Boolean indicating if the mail is deleted (used in Vault) + #[serde(alias="isDeleted")] + pub is_deleted: Option, +} + +impl RequestValue for MailItem {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *mail* resources. +/// It is not used directly, but through the `Admin` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-admin2_email_migration" as admin2_email_migration; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use admin2_email_migration::Admin; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Admin::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `insert(...)` +/// // to build up your call. +/// let rb = hub.mail(); +/// # } +/// ``` +pub struct MailMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Admin, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MailMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MailMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Insert Mail into Google's Gmail backends + pub fn insert(&self, request: &MailItem, user_key: &str) -> MailInsertCall<'a, C, NC, A> { + MailInsertCall { + hub: self.hub, + _request: request.clone(), + _user_key: user_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Insert Mail into Google's Gmail backends +/// +/// A builder for the *insert* method supported by a *mail* resource. +/// It is not used directly, but through a `MailMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-admin2_email_migration" as admin2_email_migration; +/// use admin2_email_migration::MailItem; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use admin2_email_migration::Admin; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Admin::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: MailItem = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mail().insert(&req, "userKey") +/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct MailInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Admin, + _request: MailItem, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MailInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MailInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "emailMigration.mail.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userKey", self._user_key.to_string())); + for &field in ["userKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/email/v2/users/{userKey}/mail".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/email/v2/users/{userKey}/mail".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::EmailMigration.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut mp_reader: MultiPartReader = Default::default(); + let (mut body_reader, content_type) = match protocol { + "simple" => { + mp_reader.reserve_exact(2); + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone()) + .add_part(&mut reader, size, reader_mime_type.clone()); + let mime_type = mp_reader.mime_type(); + (&mut mp_reader as &mut io::Read, ContentType(mime_type)) + }, + _ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())), + }; + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(content_type) + .body(&mut body_reader); + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 35MB + /// * *multipart*: yes + /// * *valid mime types*: 'message/rfc822' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 35MB + /// * *multipart*: yes + /// * *valid mime types*: 'message/rfc822' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &MailItem) -> MailInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The email or immutable id of the user + pub fn user_key(mut self, new_value: &str) -> MailInsertCall<'a, C, NC, A> { + self._user_key = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MailInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MailInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MailInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/adsense1d4/Cargo.toml b/gen/adsense1d4/Cargo.toml new file mode 100644 index 0000000000..5816dcd66b --- /dev/null +++ b/gen/adsense1d4/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adsense1d4" +version = "0.1.0+20150312" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with AdSense (protocol v1.4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adsense1d4" +homepage = "https://developers.google.com/adsense/management/" +documentation = "http://byron.github.io/google-apis-rs/google-adsense1d4" +license = "MIT" +keywords = ["adsense", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/adsense1d4/LICENSE.md b/gen/adsense1d4/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adsense1d4/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/adsense1d4/README.md b/gen/adsense1d4/README.md new file mode 100644 index 0000000000..d8e8a298cf --- /dev/null +++ b/gen/adsense1d4/README.md @@ -0,0 +1,213 @@ + +The `google-adsense1d4` library allows access to all features of the *Google AdSense* service. + +This documentation was generated from *AdSense* crate version *0.1.0+20150312*, where *20150312* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *AdSense* *v1d4* API can be found at the +[official documentation site](https://developers.google.com/adsense/management/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdSense.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.Account.html) + * [*adclients list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAdclientListCall.html), [*adunits customchannels list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAdunitCustomchannelListCall.html), [*adunits get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAdunitGetCall.html), [*adunits get ad code*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAdunitGetAdCodeCall.html), [*adunits list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAdunitListCall.html), [*alerts delete*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAlertDeleteCall.html), [*alerts list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountAlertListCall.html), [*customchannels adunits list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountCustomchannelAdunitListCall.html), [*customchannels get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountCustomchannelGetCall.html), [*customchannels list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountCustomchannelListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountListCall.html), [*payments list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountPaymentListCall.html), [*reports generate*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountReportGenerateCall.html), [*reports saved generate*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountReportSavedGenerateCall.html), [*reports saved list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountReportSavedListCall.html), [*savedadstyles get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountSavedadstyleGetCall.html), [*savedadstyles list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountSavedadstyleListCall.html) and [*urlchannels list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountUrlchannelListCall.html) +* adclients + * [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdclientListCall.html) +* adunits + * [*customchannels list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdunitCustomchannelListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdunitGetCall.html), [*get ad code*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdunitGetAdCodeCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdunitListCall.html) +* [alerts](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.Alert.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AlertDeleteCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AlertListCall.html) +* customchannels + * [*adunits list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.CustomchannelAdunitListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.CustomchannelGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.CustomchannelListCall.html) +* [metadata](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.Metadata.html) + * [*dimensions list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.MetadataDimensionListCall.html) and [*metrics list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.MetadataMetricListCall.html) +* [payments](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.Payment.html) + * [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.PaymentListCall.html) +* reports + * [*generate*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.ReportGenerateCall.html), [*saved generate*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.ReportSavedGenerateCall.html) and [*saved list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.ReportSavedListCall.html) +* savedadstyles + * [*get*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.SavedadstyleGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.SavedadstyleListCall.html) +* urlchannels + * [*list*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.UrlchannelListCall.html) + + +Download supported by ... + +* [*generate reports*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.ReportGenerateCall.html) +* [*reports generate accounts*](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AccountReportGenerateCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-adsense1d4/struct.AdSense.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.accounts().adunits_list(...).doit() +let r = hub.accounts().customchannels_list(...).doit() +let r = hub.accounts().adunits_customchannels_list(...).doit() +let r = hub.accounts().alerts_delete(...).doit() +let r = hub.accounts().savedadstyles_get(...).doit() +let r = hub.accounts().reports_generate(...).doit() +let r = hub.accounts().list(...).doit() +let r = hub.accounts().adclients_list(...).doit() +let r = hub.accounts().reports_saved_generate(...).doit() +let r = hub.accounts().adunits_get(...).doit() +let r = hub.accounts().alerts_list(...).doit() +let r = hub.accounts().savedadstyles_list(...).doit() +let r = hub.accounts().customchannels_get(...).doit() +let r = hub.accounts().get(...).doit() +let r = hub.accounts().customchannels_adunits_list(...).doit() +let r = hub.accounts().payments_list(...).doit() +let r = hub.accounts().adunits_get_ad_code(...).doit() +let r = hub.accounts().reports_saved_list(...).doit() +let r = hub.accounts().urlchannels_list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-adsense1d4 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-adsense1d4" as adsense1d4; +use adsense1d4::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use adsense1d4::AdSense; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AdSense::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") + .use_timezone_reporting(true) + .start_index(-85) + .add_sort("dolores") + .add_metric("kasd") + .max_results(-22) + .locale("takimata") + .add_filter("justo") + .add_dimension("amet.") + .currency("erat") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-adsense1d4/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-adsense1d4/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-adsense1d4/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-adsense1d4/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **adsense1d4** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/adsense1d4/src/cmn.rs b/gen/adsense1d4/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/adsense1d4/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/adsense1d4/src/lib.rs b/gen/adsense1d4/src/lib.rs new file mode 100644 index 0000000000..81b8fc1ecc --- /dev/null +++ b/gen/adsense1d4/src/lib.rs @@ -0,0 +1,11912 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *AdSense* crate version *0.1.0+20150312*, where *20150312* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *AdSense* *v1d4* API can be found at the +//! [official documentation site](https://developers.google.com/adsense/management/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adsense1d4). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AdSense.html) ... +//! +//! * [accounts](struct.Account.html) +//! * [*adclients list*](struct.AccountAdclientListCall.html), [*adunits customchannels list*](struct.AccountAdunitCustomchannelListCall.html), [*adunits get*](struct.AccountAdunitGetCall.html), [*adunits get ad code*](struct.AccountAdunitGetAdCodeCall.html), [*adunits list*](struct.AccountAdunitListCall.html), [*alerts delete*](struct.AccountAlertDeleteCall.html), [*alerts list*](struct.AccountAlertListCall.html), [*customchannels adunits list*](struct.AccountCustomchannelAdunitListCall.html), [*customchannels get*](struct.AccountCustomchannelGetCall.html), [*customchannels list*](struct.AccountCustomchannelListCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*payments list*](struct.AccountPaymentListCall.html), [*reports generate*](struct.AccountReportGenerateCall.html), [*reports saved generate*](struct.AccountReportSavedGenerateCall.html), [*reports saved list*](struct.AccountReportSavedListCall.html), [*savedadstyles get*](struct.AccountSavedadstyleGetCall.html), [*savedadstyles list*](struct.AccountSavedadstyleListCall.html) and [*urlchannels list*](struct.AccountUrlchannelListCall.html) +//! * adclients +//! * [*list*](struct.AdclientListCall.html) +//! * adunits +//! * [*customchannels list*](struct.AdunitCustomchannelListCall.html), [*get*](struct.AdunitGetCall.html), [*get ad code*](struct.AdunitGetAdCodeCall.html) and [*list*](struct.AdunitListCall.html) +//! * [alerts](struct.Alert.html) +//! * [*delete*](struct.AlertDeleteCall.html) and [*list*](struct.AlertListCall.html) +//! * customchannels +//! * [*adunits list*](struct.CustomchannelAdunitListCall.html), [*get*](struct.CustomchannelGetCall.html) and [*list*](struct.CustomchannelListCall.html) +//! * [metadata](struct.Metadata.html) +//! * [*dimensions list*](struct.MetadataDimensionListCall.html) and [*metrics list*](struct.MetadataMetricListCall.html) +//! * [payments](struct.Payment.html) +//! * [*list*](struct.PaymentListCall.html) +//! * reports +//! * [*generate*](struct.ReportGenerateCall.html), [*saved generate*](struct.ReportSavedGenerateCall.html) and [*saved list*](struct.ReportSavedListCall.html) +//! * savedadstyles +//! * [*get*](struct.SavedadstyleGetCall.html) and [*list*](struct.SavedadstyleListCall.html) +//! * urlchannels +//! * [*list*](struct.UrlchannelListCall.html) +//! +//! +//! Download supported by ... +//! +//! * [*generate reports*](struct.ReportGenerateCall.html) +//! * [*reports generate accounts*](struct.AccountReportGenerateCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AdSense.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.accounts().adunits_list(...).doit() +//! let r = hub.accounts().customchannels_list(...).doit() +//! let r = hub.accounts().adunits_customchannels_list(...).doit() +//! let r = hub.accounts().alerts_delete(...).doit() +//! let r = hub.accounts().savedadstyles_get(...).doit() +//! let r = hub.accounts().reports_generate(...).doit() +//! let r = hub.accounts().list(...).doit() +//! let r = hub.accounts().adclients_list(...).doit() +//! let r = hub.accounts().reports_saved_generate(...).doit() +//! let r = hub.accounts().adunits_get(...).doit() +//! let r = hub.accounts().alerts_list(...).doit() +//! let r = hub.accounts().savedadstyles_list(...).doit() +//! let r = hub.accounts().customchannels_get(...).doit() +//! let r = hub.accounts().get(...).doit() +//! let r = hub.accounts().customchannels_adunits_list(...).doit() +//! let r = hub.accounts().payments_list(...).doit() +//! let r = hub.accounts().adunits_get_ad_code(...).doit() +//! let r = hub.accounts().reports_saved_list(...).doit() +//! let r = hub.accounts().urlchannels_list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-adsense1d4 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-adsense1d4" as adsense1d4; +//! use adsense1d4::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use adsense1d4::AdSense; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AdSense::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +//! .use_timezone_reporting(true) +//! .start_index(-61) +//! .add_sort("sadipscing") +//! .add_metric("aliquyam") +//! .max_results(-66) +//! .locale("no") +//! .add_filter("justo") +//! .add_dimension("justo") +//! .currency("et") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your AdSense data + Readonly, + + /// View and manage your AdSense data + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Readonly => "https://www.googleapis.com/auth/adsense.readonly", + Scope::Full => "https://www.googleapis.com/auth/adsense", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AdSense related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// use adsense1d4::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .use_timezone_reporting(true) +/// .start_index(-21) +/// .add_sort("duo") +/// .add_metric("aliquyam") +/// .max_results(-9) +/// .locale("Lorem") +/// .add_filter("eos") +/// .add_dimension("erat") +/// .currency("sadipscing") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AdSense { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AdSense {} + +impl<'a, C, NC, A> AdSense + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AdSense { + AdSense { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + pub fn adclients(&'a self) -> AdclientMethods<'a, C, NC, A> { + AdclientMethods { hub: &self } + } + pub fn adunits(&'a self) -> AdunitMethods<'a, C, NC, A> { + AdunitMethods { hub: &self } + } + pub fn alerts(&'a self) -> AlertMethods<'a, C, NC, A> { + AlertMethods { hub: &self } + } + pub fn customchannels(&'a self) -> CustomchannelMethods<'a, C, NC, A> { + CustomchannelMethods { hub: &self } + } + pub fn metadata(&'a self) -> MetadataMethods<'a, C, NC, A> { + MetadataMethods { hub: &self } + } + pub fn payments(&'a self) -> PaymentMethods<'a, C, NC, A> { + PaymentMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, NC, A> { + ReportMethods { hub: &self } + } + pub fn savedadstyles(&'a self) -> SavedadstyleMethods<'a, C, NC, A> { + SavedadstyleMethods { hub: &self } + } + pub fn urlchannels(&'a self) -> UrlchannelMethods<'a, C, NC, A> { + UrlchannelMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list urlchannels](struct.UrlchannelListCall.html) (response) +/// * [urlchannels list accounts](struct.AccountUrlchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlChannels { + /// Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The URL channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#urlChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for UrlChannels {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits list accounts](struct.AccountAdunitListCall.html) (none) +/// * [customchannels list accounts](struct.AccountCustomchannelListCall.html) (none) +/// * [adunits customchannels list accounts](struct.AccountAdunitCustomchannelListCall.html) (none) +/// * [alerts delete accounts](struct.AccountAlertDeleteCall.html) (none) +/// * [savedadstyles get accounts](struct.AccountSavedadstyleGetCall.html) (none) +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (none) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (none) +/// * [reports saved generate accounts](struct.AccountReportSavedGenerateCall.html) (none) +/// * [adunits get accounts](struct.AccountAdunitGetCall.html) (none) +/// * [alerts list accounts](struct.AccountAlertListCall.html) (none) +/// * [savedadstyles list accounts](struct.AccountSavedadstyleListCall.html) (none) +/// * [customchannels get accounts](struct.AccountCustomchannelGetCall.html) (none) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// * [customchannels adunits list accounts](struct.AccountCustomchannelAdunitListCall.html) (none) +/// * [payments list accounts](struct.AccountPaymentListCall.html) (none) +/// * [adunits get ad code accounts](struct.AccountAdunitGetAdCodeCall.html) (none) +/// * [reports saved list accounts](struct.AccountReportSavedListCall.html) (none) +/// * [urlchannels list accounts](struct.AccountUrlchannelListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Account { + /// Kind of resource this is, in this case adsense#account. + pub kind: String, + /// Whether this account is premium. + pub premium: bool, + /// Name of this account. + pub name: String, + /// AdSense timezone of this account. + pub timezone: String, + /// Unique identifier of this account. + pub id: String, + /// Sub accounts of the this account. + #[serde(alias="subAccounts")] + pub sub_accounts: Vec, +} + +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits list accounts](struct.AccountAdunitListCall.html) (response) +/// * [list adunits](struct.AdunitListCall.html) (response) +/// * [customchannels adunits list accounts](struct.AccountCustomchannelAdunitListCall.html) (response) +/// * [adunits list customchannels](struct.CustomchannelAdunitListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnits { + /// Continuation token used to page through ad units. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The ad units returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#adUnits. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for AdUnits {} + + +/// The font which is included in the style. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdStyleFont { + /// The family of the font. + pub family: String, + /// The size of the font. + pub size: String, +} + +impl NestedType for AdStyleFont {} +impl Part for AdStyleFont {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [saved generate reports](struct.ReportSavedGenerateCall.html) (response) +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (response) +/// * [reports saved generate accounts](struct.AccountReportSavedGenerateCall.html) (response) +/// * [generate reports](struct.ReportGenerateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdsenseReportsGenerateResponse { + /// The requested start date in yyyy-mm-dd format. + #[serde(alias="startDate")] + pub start_date: String, + /// Kind this is, in this case adsense#report. + pub kind: String, + /// The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The dimension cells contain strings, and the metric cells contain numbers. + pub rows: Vec>, + /// The requested end date in yyyy-mm-dd format. + #[serde(alias="endDate")] + pub end_date: String, + /// Any warnings associated with generation of the report. + pub warnings: Vec, + /// The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub totals: Vec, + /// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. + pub headers: Vec, + /// The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or the report row limit. + #[serde(alias="totalMatchedRows")] + pub total_matched_rows: String, + /// The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub averages: Vec, +} + +impl ResponseResult for AdsenseReportsGenerateResponse {} + + +/// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdsenseReportsGenerateResponseHeaders { + /// The currency of this column. Only present if the header type is METRIC_CURRENCY. + pub currency: String, + /// The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY. + #[serde(alias="type")] + pub type_: String, + /// The name of the header. + pub name: String, +} + +impl NestedType for AdsenseReportsGenerateResponseHeaders {} +impl Part for AdsenseReportsGenerateResponseHeaders {} + + +/// Settings specific to WAP mobile content ads (AFMC). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnitMobileContentAdsSettings { + /// The scripting language to use for this ad unit. + #[serde(alias="scriptingLanguage")] + pub scripting_language: String, + /// The markup language to use for this ad unit. + #[serde(alias="markupLanguage")] + pub markup_language: String, + /// Type of this ad unit. + #[serde(alias="type")] + pub type_: String, + /// Size of this ad unit. + pub size: String, +} + +impl NestedType for AdUnitMobileContentAdsSettings {} +impl Part for AdUnitMobileContentAdsSettings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [alerts list accounts](struct.AccountAlertListCall.html) (response) +/// * [list alerts](struct.AlertListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Alerts { + /// The alerts returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#alerts. + pub kind: String, +} + +impl ResponseResult for Alerts {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedReport { + /// Kind of resource this is, in this case adsense#savedReport. + pub kind: String, + /// Unique identifier of this saved report. + pub id: String, + /// This saved report's name. + pub name: String, +} + +impl Part for SavedReport {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClient { + /// ARC review mode this ad client is in. Empty if the client is not opted in to ARC. Possible values: POST_REVIEW, AUTOMATIC_PRE_REVIEW. + #[serde(alias="arcReviewMode")] + pub arc_review_mode: String, + /// This ad client's product code, which corresponds to the PRODUCT_CODE report dimension. + #[serde(alias="productCode")] + pub product_code: String, + /// Kind of resource this is, in this case adsense#adClient. + pub kind: String, + /// Whether this ad client is opted in to ARC. + #[serde(alias="arcOptIn")] + pub arc_opt_in: bool, + /// Whether this ad client supports being reported on. + #[serde(alias="supportsReporting")] + pub supports_reporting: bool, + /// Unique identifier of this ad client. + pub id: String, +} + +impl Part for AdClient {} + + +/// The backup option to be used in instances where no ad is available. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnitContentAdsSettingsBackupOption { + /// Color to use when type is set to COLOR. + pub color: String, + /// URL to use when type is set to URL. + pub url: String, + /// Type of the backup option. Possible values are BLANK, COLOR and URL. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for AdUnitContentAdsSettingsBackupOption {} +impl Part for AdUnitContentAdsSettingsBackupOption {} + + +/// Settings specific to feed ads (AFF). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnitFeedAdsSettings { + /// The minimum length an entry should be in order to have attached ads. + #[serde(alias="minimumWordCount")] + pub minimum_word_count: i32, + /// The frequency at which ads should appear in the feed (i.e. every N entries). + pub frequency: i32, + /// The position of the ads relative to the feed entries. + #[serde(alias="adPosition")] + pub ad_position: String, + /// The type of ads which should appear. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for AdUnitFeedAdsSettings {} +impl Part for AdUnitFeedAdsSettings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [payments list accounts](struct.AccountPaymentListCall.html) (response) +/// * [list payments](struct.PaymentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Payments { + /// The list of Payments for the account. One or both of a) the account's most recent payment; and b) the account's upcoming payment. + pub items: Vec, + /// Kind of list this is, in this case adsense#payments. + pub kind: String, +} + +impl ResponseResult for Payments {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportingMetadataEntry { + /// The names of the metrics which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report to be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted. + #[serde(alias="requiredMetrics")] + pub required_metrics: Vec, + /// Kind of resource this is, in this case adsense#reportingMetadataEntry. + pub kind: String, + /// The names of the metrics the dimension or metric this reporting metadata entry describes is compatible with. + #[serde(alias="compatibleMetrics")] + pub compatible_metrics: Vec, + /// For metrics this is a list of dimension IDs which the metric is compatible with, for dimensions it is a list of compatibility groups the dimension belongs to. + #[serde(alias="compatibleDimensions")] + pub compatible_dimensions: Vec, + /// Unique identifier of this reporting metadata entry, corresponding to the name of the appropriate dimension or metric. + pub id: String, + /// The names of the dimensions which the dimension or metric this reporting metadata entry describes requires to also be present in order for the report to be valid. Omitting these will not cause an error or warning, but may result in data which cannot be correctly interpreted. + #[serde(alias="requiredDimensions")] + pub required_dimensions: Vec, + /// The codes of the projects supported by the dimension or metric this reporting metadata entry describes. + #[serde(alias="supportedProducts")] + pub supported_products: Vec, +} + +impl Part for ReportingMetadataEntry {} + + +/// The targeting information of this custom channel, if activated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannelTargetingInfo { + /// The external description of the channel. + pub description: String, + /// The language of the sites ads will be displayed on. + #[serde(alias="siteLanguage")] + pub site_language: String, + /// The locations in which ads appear. (Only valid for content and mobile content ads). Acceptable values for content ads are: TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, MULTIPLE_LOCATIONS. Acceptable values for mobile content ads are: TOP, MIDDLE, BOTTOM, MULTIPLE_LOCATIONS. + pub location: String, + /// The name used to describe this channel externally. + #[serde(alias="adsAppearOn")] + pub ads_appear_on: String, +} + +impl NestedType for CustomChannelTargetingInfo {} +impl Part for CustomChannelTargetingInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [customchannels list accounts](struct.AccountCustomchannelListCall.html) (response) +/// * [customchannels list adunits](struct.AdunitCustomchannelListCall.html) (response) +/// * [adunits customchannels list accounts](struct.AccountAdunitCustomchannelListCall.html) (response) +/// * [list customchannels](struct.CustomchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannels { + /// Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The custom channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#customChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for CustomChannels {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlChannel { + /// Kind of resource this is, in this case adsense#urlChannel. + pub kind: String, + /// Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// URL Pattern of this URL channel. Does not include "http://" or "https://". Example: www.example.com/home + #[serde(alias="urlPattern")] + pub url_pattern: String, +} + +impl Part for UrlChannel {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get adunits](struct.AdunitGetCall.html) (response) +/// * [adunits get accounts](struct.AccountAdunitGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnit { + /// Status of this ad unit. Possible values are: + /// NEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it. + /// + /// ACTIVE: Indicates that there has been activity on this ad unit in the last seven days. + /// + /// INACTIVE: Indicates that there has been no activity on this ad unit in the last seven days. + pub status: String, + /// Kind of resource this is, in this case adsense#adUnit. + pub kind: String, + /// Identity code of this ad unit, not necessarily unique across ad clients. + pub code: String, + /// Name of this ad unit. + pub name: String, + /// Settings specific to feed ads (AFF). + #[serde(alias="feedAdsSettings")] + pub feed_ads_settings: AdUnitFeedAdsSettings, + /// ID of the saved ad style which holds this ad unit's style information. + #[serde(alias="savedStyleId")] + pub saved_style_id: String, + /// Settings specific to content ads (AFC) and highend mobile content ads (AFMC). + #[serde(alias="contentAdsSettings")] + pub content_ads_settings: AdUnitContentAdsSettings, + /// Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// Settings specific to WAP mobile content ads (AFMC). + #[serde(alias="mobileContentAdsSettings")] + pub mobile_content_ads_settings: AdUnitMobileContentAdsSettings, + /// Custom style information specific to this ad unit. + #[serde(alias="customStyle")] + pub custom_style: AdStyle, +} + +impl Resource for AdUnit {} +impl ResponseResult for AdUnit {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list adclients](struct.AdclientListCall.html) (response) +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClients { + /// Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The ad clients returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#adClients. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for AdClients {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdStyle { + /// The style of the corners in the ad. + pub corners: String, + /// The colors which are included in the style. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading hash. + pub colors: AdStyleColors, + /// The font which is included in the style. + pub font: AdStyleFont, + /// Kind this is, in this case adsense#adStyle. + pub kind: String, +} + +impl Part for AdStyle {} + + +/// The colors which are included in the style. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading hash. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdStyleColors { + /// The color of the ad url. + pub url: String, + /// The color of the ad text. + pub text: String, + /// The color of the ad border. + pub border: String, + /// The color of the ad background. + pub background: String, + /// The color of the ad title. + pub title: String, +} + +impl NestedType for AdStyleColors {} +impl Part for AdStyleColors {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [saved list reports](struct.ReportSavedListCall.html) (response) +/// * [reports saved list accounts](struct.AccountReportSavedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedReports { + /// Continuation token used to page through saved reports. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The saved reports returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#savedReports. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for SavedReports {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [savedadstyles list accounts](struct.AccountSavedadstyleListCall.html) (response) +/// * [list savedadstyles](struct.SavedadstyleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedAdStyles { + /// Continuation token used to page through ad units. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The saved ad styles returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#savedAdStyles. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for SavedAdStyles {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list alerts](struct.AlertListCall.html) (none) +/// * [delete alerts](struct.AlertDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Alert { + /// Kind of resource this is, in this case adsense#alert. + pub kind: Option, + /// Severity of this alert. Possible values: INFO, WARNING, SEVERE. + pub severity: Option, + /// Whether this alert can be dismissed. + #[serde(alias="isDismissible")] + pub is_dismissible: Option, + /// The localized alert message. + pub message: Option, + /// Type of this alert. Possible values: SELF_HOLD, MIGRATED_TO_BILLING3, ADDRESS_PIN_VERIFICATION, PHONE_PIN_VERIFICATION, CORPORATE_ENTITY, GRAYLISTED_PUBLISHER, API_HOLD. + #[serde(alias="type")] + pub type_: Option, + /// Unique identifier of this alert. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: Option, +} + +impl Resource for Alert {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [customchannels get accounts](struct.AccountCustomchannelGetCall.html) (response) +/// * [get customchannels](struct.CustomchannelGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannel { + /// Kind of resource this is, in this case adsense#customChannel. + pub kind: String, + /// Code of this custom channel, not necessarily unique across ad clients. + pub code: String, + /// The targeting information of this custom channel, if activated. + #[serde(alias="targetingInfo")] + pub targeting_info: CustomChannelTargetingInfo, + /// Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// Name of this custom channel. + pub name: String, +} + +impl Resource for CustomChannel {} +impl ResponseResult for CustomChannel {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Accounts { + /// Continuation token used to page through accounts. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The accounts returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsense#accounts. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for Accounts {} + + +/// Settings specific to content ads (AFC) and highend mobile content ads (AFMC). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnitContentAdsSettings { + /// Type of this ad unit. + #[serde(alias="type")] + pub type_: String, + /// The backup option to be used in instances where no ad is available. + #[serde(alias="backupOption")] + pub backup_option: AdUnitContentAdsSettingsBackupOption, + /// Size of this ad unit. + pub size: String, +} + +impl NestedType for AdUnitContentAdsSettings {} +impl Part for AdUnitContentAdsSettings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get savedadstyles](struct.SavedadstyleGetCall.html) (response) +/// * [savedadstyles get accounts](struct.AccountSavedadstyleGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedAdStyle { + /// Kind of resource this is, in this case adsense#savedAdStyle. + pub kind: String, + /// Unique identifier of this saved ad style. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: String, + /// The AdStyle itself. + #[serde(alias="adStyle")] + pub ad_style: AdStyle, + /// The user selected name of this SavedAdStyle. + pub name: String, +} + +impl Resource for SavedAdStyle {} +impl ResponseResult for SavedAdStyle {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits get ad code accounts](struct.AccountAdunitGetAdCodeCall.html) (response) +/// * [get ad code adunits](struct.AdunitGetAdCodeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdCode { + /// The ad code snippet. + #[serde(alias="adCode")] + pub ad_code: String, + /// Kind this is, in this case adsense#adCode. + pub kind: String, +} + +impl ResponseResult for AdCode {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [metrics list metadata](struct.MetadataMetricListCall.html) (response) +/// * [dimensions list metadata](struct.MetadataDimensionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Metadata { + /// no description provided + pub items: Vec, + /// Kind of list this is, in this case adsense#metadata. + pub kind: String, +} + +impl ResponseResult for Metadata {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list payments](struct.PaymentListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Payment { + /// The currency code for the amount to be paid. + #[serde(alias="paymentAmountCurrencyCode")] + pub payment_amount_currency_code: Option, + /// Kind of resource this is, in this case adsense#payment. + pub kind: Option, + /// The amount to be paid. + #[serde(alias="paymentAmount")] + pub payment_amount: Option, + /// Unique identifier of this Payment. + pub id: Option, + /// The date this payment was/will be credited to the user, or none if the payment threshold has not been met. + #[serde(alias="paymentDate")] + pub payment_date: Option, +} + +impl Resource for Payment {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *urlchannel* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.urlchannels(); +/// # } +/// ``` +pub struct UrlchannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UrlchannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all URL channels in the specified ad client for this AdSense account. + pub fn list(&self, ad_client_id: &str) -> UrlchannelListCall<'a, C, NC, A> { + UrlchannelListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *adunit* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `customchannels_list(...)`, `get(...)`, `get_ad_code(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.adunits(); +/// # } +/// ``` +pub struct AdunitMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdunitMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdunitMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all custom channels which the specified ad unit belongs to. + pub fn customchannels_list(&self, ad_client_id: &str, ad_unit_id: &str) -> AdunitCustomchannelListCall<'a, C, NC, A> { + AdunitCustomchannelListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the specified ad unit in the specified ad client. + pub fn get(&self, ad_client_id: &str, ad_unit_id: &str) -> AdunitGetCall<'a, C, NC, A> { + AdunitGetCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad units in the specified ad client for this AdSense account. + pub fn list(&self, ad_client_id: &str) -> AdunitListCall<'a, C, NC, A> { + AdunitListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_inactive: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get ad code for the specified ad unit. + pub fn get_ad_code(&self, ad_client_id: &str, ad_unit_id: &str) -> AdunitGetAdCodeCall<'a, C, NC, A> { + AdunitGetAdCodeCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *adclient* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.adclients(); +/// # } +/// ``` +pub struct AdclientMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdclientMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdclientMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all ad clients in this AdSense account. + pub fn list(&self) -> AdclientListCall<'a, C, NC, A> { + AdclientListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *alert* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.alerts(); +/// # } +/// ``` +pub struct AlertMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AlertMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AlertMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Dismiss (delete) the specified alert from the publisher's AdSense account. + pub fn delete(&self, alert_id: &str) -> AlertDeleteCall<'a, C, NC, A> { + AlertDeleteCall { + hub: self.hub, + _alert_id: alert_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the alerts for this AdSense account. + pub fn list(&self) -> AlertListCall<'a, C, NC, A> { + AlertListCall { + hub: self.hub, + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *savedadstyle* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.savedadstyles(); +/// # } +/// ``` +pub struct SavedadstyleMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SavedadstyleMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SavedadstyleMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all saved ad styles in the user's account. + pub fn list(&self) -> SavedadstyleListCall<'a, C, NC, A> { + SavedadstyleListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get a specific saved ad style from the user's account. + pub fn get(&self, saved_ad_style_id: &str) -> SavedadstyleGetCall<'a, C, NC, A> { + SavedadstyleGetCall { + hub: self.hub, + _saved_ad_style_id: saved_ad_style_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *report* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generate(...)`, `saved_generate(...)` and `saved_list(...)` +/// // to build up your call. +/// let rb = hub.reports(); +/// # } +/// ``` +pub struct ReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all saved reports in this AdSense account. + pub fn saved_list(&self) -> ReportSavedListCall<'a, C, NC, A> { + ReportSavedListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. + pub fn generate(&self, start_date: &str, end_date: &str) -> ReportGenerateCall<'a, C, NC, A> { + ReportGenerateCall { + hub: self.hub, + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _use_timezone_reporting: Default::default(), + _start_index: Default::default(), + _sort: Default::default(), + _metric: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _filter: Default::default(), + _dimension: Default::default(), + _currency: Default::default(), + _account_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the saved report ID sent in the query parameters. + pub fn saved_generate(&self, saved_report_id: &str) -> ReportSavedGenerateCall<'a, C, NC, A> { + ReportSavedGenerateCall { + hub: self.hub, + _saved_report_id: saved_report_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `adclients_list(...)`, `adunits_customchannels_list(...)`, `adunits_get(...)`, `adunits_get_ad_code(...)`, `adunits_list(...)`, `alerts_delete(...)`, `alerts_list(...)`, `customchannels_adunits_list(...)`, `customchannels_get(...)`, `customchannels_list(...)`, `get(...)`, `list(...)`, `payments_list(...)`, `reports_generate(...)`, `reports_saved_generate(...)`, `reports_saved_list(...)`, `savedadstyles_get(...)`, `savedadstyles_list(...)` and `urlchannels_list(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Dismiss (delete) the specified alert from the specified publisher AdSense account. + pub fn alerts_delete(&self, account_id: &str, alert_id: &str) -> AccountAlertDeleteCall<'a, C, NC, A> { + AccountAlertDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _alert_id: alert_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the alerts for the specified AdSense account. + pub fn alerts_list(&self, account_id: &str) -> AccountAlertListCall<'a, C, NC, A> { + AccountAlertListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the saved report ID sent in the query parameters. + pub fn reports_saved_generate(&self, account_id: &str, saved_report_id: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + AccountReportSavedGenerateCall { + hub: self.hub, + _account_id: account_id.to_string(), + _saved_report_id: saved_report_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all accounts available to this AdSense account. + pub fn list(&self) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the payments for the specified AdSense account. + pub fn payments_list(&self, account_id: &str) -> AccountPaymentListCall<'a, C, NC, A> { + AccountPaymentListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List a specific saved ad style for the specified account. + pub fn savedadstyles_get(&self, account_id: &str, saved_ad_style_id: &str) -> AccountSavedadstyleGetCall<'a, C, NC, A> { + AccountSavedadstyleGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _saved_ad_style_id: saved_ad_style_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the specified ad unit in the specified ad client for the specified account. + pub fn adunits_get(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + AccountAdunitGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get the specified custom channel from the specified ad client for the specified account. + pub fn customchannels_get(&self, account_id: &str, ad_client_id: &str, custom_channel_id: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + AccountCustomchannelGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad units in the specified custom channel. + pub fn customchannels_adunits_list(&self, account_id: &str, ad_client_id: &str, custom_channel_id: &str) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + AccountCustomchannelAdunitListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_inactive: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all saved reports in the specified AdSense account. + pub fn reports_saved_list(&self, account_id: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + AccountReportSavedListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all URL channels in the specified ad client for the specified account. + pub fn urlchannels_list(&self, account_id: &str, ad_client_id: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + AccountUrlchannelListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad units in the specified ad client for the specified account. + pub fn adunits_list(&self, account_id: &str, ad_client_id: &str) -> AccountAdunitListCall<'a, C, NC, A> { + AccountAdunitListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_inactive: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. + pub fn reports_generate(&self, account_id: &str, start_date: &str, end_date: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + AccountReportGenerateCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _use_timezone_reporting: Default::default(), + _start_index: Default::default(), + _sort: Default::default(), + _metric: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _filter: Default::default(), + _dimension: Default::default(), + _currency: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad clients in the specified account. + pub fn adclients_list(&self, account_id: &str) -> AccountAdclientListCall<'a, C, NC, A> { + AccountAdclientListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all custom channels in the specified ad client for the specified account. + pub fn customchannels_list(&self, account_id: &str, ad_client_id: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + AccountCustomchannelListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all saved ad styles in the specified account. + pub fn savedadstyles_list(&self, account_id: &str) -> AccountSavedadstyleListCall<'a, C, NC, A> { + AccountSavedadstyleListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get ad code for the specified ad unit. + pub fn adunits_get_ad_code(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + AccountAdunitGetAdCodeCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all custom channels which the specified ad unit belongs to. + pub fn adunits_customchannels_list(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + AccountAdunitCustomchannelListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about the selected AdSense account. + pub fn get(&self, account_id: &str) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _tree: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *payment* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.payments(); +/// # } +/// ``` +pub struct PaymentMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PaymentMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PaymentMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List the payments for this AdSense account. + pub fn list(&self) -> PaymentListCall<'a, C, NC, A> { + PaymentListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *metadata* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `dimensions_list(...)` and `metrics_list(...)` +/// // to build up your call. +/// let rb = hub.metadata(); +/// # } +/// ``` +pub struct MetadataMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MetadataMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetadataMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List the metadata for the dimensions available to this AdSense account. + pub fn dimensions_list(&self) -> MetadataDimensionListCall<'a, C, NC, A> { + MetadataDimensionListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the metadata for the metrics available to this AdSense account. + pub fn metrics_list(&self) -> MetadataMetricListCall<'a, C, NC, A> { + MetadataMetricListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *customchannel* resources. +/// It is not used directly, but through the `AdSense` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsense1d4" as adsense1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsense1d4::AdSense; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `adunits_list(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.customchannels(); +/// # } +/// ``` +pub struct CustomchannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CustomchannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Get the specified custom channel from the specified ad client. + pub fn get(&self, ad_client_id: &str, custom_channel_id: &str) -> CustomchannelGetCall<'a, C, NC, A> { + CustomchannelGetCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all custom channels in the specified ad client for this AdSense account. + pub fn list(&self, ad_client_id: &str) -> CustomchannelListCall<'a, C, NC, A> { + CustomchannelListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all ad units in the specified custom channel. + pub fn adunits_list(&self, ad_client_id: &str, custom_channel_id: &str) -> CustomchannelAdunitListCall<'a, C, NC, A> { + CustomchannelAdunitListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_inactive: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// List all URL channels in the specified ad client for this AdSense account. +/// +/// A builder for the *list* method supported by a *urlchannel* resource. +/// It is not used directly, but through a `UrlchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.urlchannels().list("adClientId") +/// .page_token("eirmod") +/// .max_results(-43) +/// .doit(); +/// # } +/// ``` +pub struct UrlchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.urlchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/urlchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list URL channels. + pub fn ad_client_id(mut self, new_value: &str) -> UrlchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> UrlchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of URL channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> UrlchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all custom channels which the specified ad unit belongs to. +/// +/// A builder for the *customchannels.list* method supported by a *adunit* resource. +/// It is not used directly, but through a `AdunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adunits().customchannels_list("adClientId", "adUnitId") +/// .page_token("labore") +/// .max_results(-39) +/// .doit(); +/// # } +/// ``` +pub struct AdunitCustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _ad_unit_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdunitCustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdunitCustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.adunits.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "adClientId", "adUnitId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/adunits/{adUnitId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AdunitCustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit for which to list custom channels. + pub fn ad_unit_id(mut self, new_value: &str) -> AdunitCustomchannelListCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AdunitCustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AdunitCustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdunitCustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdunitCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdunitCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the specified ad unit in the specified ad client. +/// +/// A builder for the *get* method supported by a *adunit* resource. +/// It is not used directly, but through a `AdunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adunits().get("adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AdunitGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdunitGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdunitGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.adunits.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/adunits/{adUnitId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to get the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AdunitGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to retrieve. + pub fn ad_unit_id(mut self, new_value: &str) -> AdunitGetCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdunitGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdunitGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdunitGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad units in the specified ad client for this AdSense account. +/// +/// A builder for the *list* method supported by a *adunit* resource. +/// It is not used directly, but through a `AdunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adunits().list("adClientId") +/// .page_token("accusam") +/// .max_results(-56) +/// .include_inactive(true) +/// .doit(); +/// # } +/// ``` +pub struct AdunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.adunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "adClientId", "pageToken", "maxResults", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list ad units. + pub fn ad_client_id(mut self, new_value: &str) -> AdunitListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AdunitListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad units to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AdunitListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include inactive* query property to the given value. + /// + /// + /// Whether to include inactive ad units. Default: true. + pub fn include_inactive(mut self, new_value: bool) -> AdunitListCall<'a, C, NC, A> { + self._include_inactive = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get ad code for the specified ad unit. +/// +/// A builder for the *getAdCode* method supported by a *adunit* resource. +/// It is not used directly, but through a `AdunitMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adunits().get_ad_code("adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AdunitGetAdCodeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdunitGetAdCodeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdunitGetAdCodeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdCode)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.adunits.getAdCode", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/adunits/{adUnitId}/adcode".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client with contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to get the code for. + pub fn ad_unit_id(mut self, new_value: &str) -> AdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdunitGetAdCodeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad clients in this AdSense account. +/// +/// A builder for the *list* method supported by a *adclient* resource. +/// It is not used directly, but through a `AdclientMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adclients().list() +/// .page_token("et") +/// .max_results(-40) +/// .doit(); +/// # } +/// ``` +pub struct AdclientListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdclientListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdclientListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClients)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.adclients.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AdclientListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad clients to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AdclientListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdclientListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdclientListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdclientListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Dismiss (delete) the specified alert from the publisher's AdSense account. +/// +/// A builder for the *delete* method supported by a *alert* resource. +/// It is not used directly, but through a `AlertMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.alerts().delete("alertId") +/// .doit(); +/// # } +/// ``` +pub struct AlertDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _alert_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AlertDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AlertDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.alerts.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("alertId", self._alert_id.to_string())); + for &field in ["alertId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/adsense/v1.4/alerts/{alertId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{alertId}", "alertId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["alertId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *alert id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Alert to delete. + pub fn alert_id(mut self, new_value: &str) -> AlertDeleteCall<'a, C, NC, A> { + self._alert_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AlertDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AlertDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AlertDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the alerts for this AdSense account. +/// +/// A builder for the *list* method supported by a *alert* resource. +/// It is not used directly, but through a `AlertMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.alerts().list() +/// .locale("et") +/// .doit(); +/// # } +/// ``` +pub struct AlertListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AlertListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AlertListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Alerts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.alerts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/alerts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale to use for translating alert messages. The account locale will be used if this is not supplied. The AdSense default (English) will be used if the supplied locale is invalid or unsupported. + pub fn locale(mut self, new_value: &str) -> AlertListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AlertListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AlertListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AlertListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all saved ad styles in the user's account. +/// +/// A builder for the *list* method supported by a *savedadstyle* resource. +/// It is not used directly, but through a `SavedadstyleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.savedadstyles().list() +/// .page_token("amet") +/// .max_results(-23) +/// .doit(); +/// # } +/// ``` +pub struct SavedadstyleListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SavedadstyleListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SavedadstyleListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedAdStyles)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.savedadstyles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/savedadstyles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through saved ad styles. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> SavedadstyleListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of saved ad styles to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> SavedadstyleListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SavedadstyleListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SavedadstyleListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SavedadstyleListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get a specific saved ad style from the user's account. +/// +/// A builder for the *get* method supported by a *savedadstyle* resource. +/// It is not used directly, but through a `SavedadstyleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.savedadstyles().get("savedAdStyleId") +/// .doit(); +/// # } +/// ``` +pub struct SavedadstyleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _saved_ad_style_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SavedadstyleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SavedadstyleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedAdStyle)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.savedadstyles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("savedAdStyleId", self._saved_ad_style_id.to_string())); + for &field in ["alt", "savedAdStyleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/savedadstyles/{savedAdStyleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{savedAdStyleId}", "savedAdStyleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["savedAdStyleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *saved ad style id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Saved ad style to retrieve. + pub fn saved_ad_style_id(mut self, new_value: &str) -> SavedadstyleGetCall<'a, C, NC, A> { + self._saved_ad_style_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SavedadstyleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SavedadstyleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SavedadstyleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all saved reports in this AdSense account. +/// +/// A builder for the *saved.list* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().saved_list() +/// .page_token("ut") +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct ReportSavedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportSavedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportSavedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.reports.saved.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/reports/saved".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> ReportSavedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of saved reports to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> ReportSavedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportSavedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportSavedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportSavedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `AdsenseReportsGenerateResponse` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *generate* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().generate("startDate", "endDate") +/// .use_timezone_reporting(true) +/// .start_index(-48) +/// .add_sort("et") +/// .add_metric("consetetur") +/// .max_results(-52) +/// .locale("voluptua.") +/// .add_filter("Lorem") +/// .add_dimension("gubergren") +/// .currency("justo") +/// .add_account_id("sit") +/// .doit(); +/// # } +/// ``` +pub struct ReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _start_date: String, + _end_date: String, + _use_timezone_reporting: Option, + _start_index: Option, + _sort: Vec, + _metric: Vec, + _max_results: Option, + _locale: Option, + _filter: Vec, + _dimension: Vec, + _currency: Option, + _account_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdsenseReportsGenerateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.reports.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("startDate", self._start_date.to_string())); + params.push(("endDate", self._end_date.to_string())); + if let Some(value) = self._use_timezone_reporting { + params.push(("useTimezoneReporting", value.to_string())); + } + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if self._sort.len() > 0 { + let mut s = String::new(); + for f in self._sort.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sort", s)); + } + if self._metric.len() > 0 { + let mut s = String::new(); + for f in self._metric.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("metric", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if self._dimension.len() > 0 { + let mut s = String::new(); + for f in self._dimension.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dimension", s)); + } + if let Some(value) = self._currency { + params.push(("currency", value.to_string())); + } + if self._account_id.len() > 0 { + let mut s = String::new(); + for f in self._account_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("accountId", s)); + } + for &field in ["startDate", "endDate", "useTimezoneReporting", "startIndex", "sort", "metric", "maxResults", "locale", "filter", "dimension", "currency", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/adsense/v1.4/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn start_date(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn end_date(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *use timezone reporting* query property to the given value. + /// + /// + /// Whether the report should be generated in the AdSense account's local timezone. If false default PST/PDT timezone will be used. + pub fn use_timezone_reporting(mut self, new_value: bool) -> ReportGenerateCall<'a, C, NC, A> { + self._use_timezone_reporting = Some(new_value); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: i32) -> ReportGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Append the given value to the *sort* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. + pub fn add_sort(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._sort.push(new_value.to_string()); + self + } + /// Append the given value to the *metric* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Numeric columns to include in the report. + pub fn add_metric(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._metric.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: i32) -> ReportGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filters to be run on the report. + pub fn add_filter(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Append the given value to the *dimension* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Dimensions to base the report on. + pub fn add_dimension(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._dimension.push(new_value.to_string()); + self + } + /// Sets the *currency* query property to the given value. + /// + /// + /// Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set. + pub fn currency(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._currency = Some(new_value.to_string()); + self + } + /// Append the given value to the *account id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Accounts upon which to report. + pub fn add_account_id(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._account_id.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the saved report ID sent in the query parameters. +/// +/// A builder for the *saved.generate* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().saved_generate("savedReportId") +/// .start_index(-28) +/// .max_results(-66) +/// .locale("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct ReportSavedGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _saved_report_id: String, + _start_index: Option, + _max_results: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportSavedGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportSavedGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdsenseReportsGenerateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.reports.saved.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("savedReportId", self._saved_report_id.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "savedReportId", "startIndex", "maxResults", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/reports/{savedReportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{savedReportId}", "savedReportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["savedReportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *saved report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The saved report to retrieve. + pub fn saved_report_id(mut self, new_value: &str) -> ReportSavedGenerateCall<'a, C, NC, A> { + self._saved_report_id = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: i32) -> ReportSavedGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: i32) -> ReportSavedGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> ReportSavedGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportSavedGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Dismiss (delete) the specified alert from the specified publisher AdSense account. +/// +/// A builder for the *alerts.delete* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().alerts_delete("accountId", "alertId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAlertDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _alert_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAlertDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAlertDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.alerts.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("alertId", self._alert_id.to_string())); + for &field in ["accountId", "alertId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/alerts/{alertId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{alertId}", "alertId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "alertId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad unit. + pub fn account_id(mut self, new_value: &str) -> AccountAlertDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *alert id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Alert to delete. + pub fn alert_id(mut self, new_value: &str) -> AccountAlertDeleteCall<'a, C, NC, A> { + self._alert_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAlertDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAlertDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAlertDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the alerts for the specified AdSense account. +/// +/// A builder for the *alerts.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().alerts_list("accountId") +/// .locale("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct AccountAlertListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAlertListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAlertListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Alerts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.alerts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "accountId", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/alerts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to retrieve the alerts. + pub fn account_id(mut self, new_value: &str) -> AccountAlertListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale to use for translating alert messages. The account locale will be used if this is not supplied. The AdSense default (English) will be used if the supplied locale is invalid or unsupported. + pub fn locale(mut self, new_value: &str) -> AccountAlertListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAlertListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAlertListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAlertListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the saved report ID sent in the query parameters. +/// +/// A builder for the *reports.saved.generate* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_saved_generate("accountId", "savedReportId") +/// .start_index(-19) +/// .max_results(-82) +/// .locale("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct AccountReportSavedGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _saved_report_id: String, + _start_index: Option, + _max_results: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportSavedGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportSavedGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdsenseReportsGenerateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.reports.saved.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("savedReportId", self._saved_report_id.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "accountId", "savedReportId", "startIndex", "maxResults", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/reports/{savedReportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{savedReportId}", "savedReportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "savedReportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the saved reports belong. + pub fn account_id(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *saved report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The saved report to retrieve. + pub fn saved_report_id(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._saved_report_id = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: i32) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: i32) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportSavedGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportSavedGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all accounts available to this AdSense account. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list() +/// .page_token("et") +/// .max_results(-13) +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Accounts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through accounts. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of accounts to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the payments for the specified AdSense account. +/// +/// A builder for the *payments.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().payments_list("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPaymentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPaymentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPaymentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Payments)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.payments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/payments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to retrieve the payments. + pub fn account_id(mut self, new_value: &str) -> AccountPaymentListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPaymentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPaymentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPaymentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List a specific saved ad style for the specified account. +/// +/// A builder for the *savedadstyles.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().savedadstyles_get("accountId", "savedAdStyleId") +/// .doit(); +/// # } +/// ``` +pub struct AccountSavedadstyleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _saved_ad_style_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountSavedadstyleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountSavedadstyleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedAdStyle)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.savedadstyles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("savedAdStyleId", self._saved_ad_style_id.to_string())); + for &field in ["alt", "accountId", "savedAdStyleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/savedadstyles/{savedAdStyleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{savedAdStyleId}", "savedAdStyleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "savedAdStyleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to get the saved ad style. + pub fn account_id(mut self, new_value: &str) -> AccountSavedadstyleGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *saved ad style id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Saved ad style to retrieve. + pub fn saved_ad_style_id(mut self, new_value: &str) -> AccountSavedadstyleGetCall<'a, C, NC, A> { + self._saved_ad_style_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountSavedadstyleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountSavedadstyleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountSavedadstyleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the specified ad unit in the specified ad client for the specified account. +/// +/// A builder for the *adunits.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_get("accountId", "adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.adunits.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to get the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to retrieve. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get the specified custom channel from the specified ad client for the specified account. +/// +/// A builder for the *customchannels.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().customchannels_get("accountId", "adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct AccountCustomchannelGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustomchannelGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustomchannelGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.customchannels.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to retrieve. + pub fn custom_channel_id(mut self, new_value: &str) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustomchannelGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad units in the specified custom channel. +/// +/// A builder for the *customchannels.adunits.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().customchannels_adunits_list("accountId", "adClientId", "customChannelId") +/// .page_token("dolore") +/// .max_results(-41) +/// .include_inactive(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountCustomchannelAdunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _custom_channel_id: String, + _page_token: Option, + _max_results: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustomchannelAdunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustomchannelAdunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.customchannels.adunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "customChannelId", "pageToken", "maxResults", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel for which to list ad units. + pub fn custom_channel_id(mut self, new_value: &str) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad units to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include inactive* query property to the given value. + /// + /// + /// Whether to include inactive ad units. Default: true. + pub fn include_inactive(mut self, new_value: bool) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._include_inactive = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustomchannelAdunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all saved reports in the specified AdSense account. +/// +/// A builder for the *reports.saved.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_saved_list("accountId") +/// .page_token("sit") +/// .max_results(-40) +/// .doit(); +/// # } +/// ``` +pub struct AccountReportSavedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportSavedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportSavedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.reports.saved.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/reports/saved".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the saved reports belong. + pub fn account_id(mut self, new_value: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountReportSavedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of saved reports to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountReportSavedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportSavedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportSavedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportSavedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all URL channels in the specified ad client for the specified account. +/// +/// A builder for the *urlchannels.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().urlchannels_list("accountId", "adClientId") +/// .page_token("sed") +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct AccountUrlchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUrlchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUrlchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.urlchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/urlchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list URL channels. + pub fn ad_client_id(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of URL channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUrlchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUrlchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUrlchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad units in the specified ad client for the specified account. +/// +/// A builder for the *adunits.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_list("accountId", "adClientId") +/// .page_token("eos") +/// .max_results(-38) +/// .include_inactive(false) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.adunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list ad units. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad units to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountAdunitListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include inactive* query property to the given value. + /// + /// + /// Whether to include inactive ad units. Default: true. + pub fn include_inactive(mut self, new_value: bool) -> AccountAdunitListCall<'a, C, NC, A> { + self._include_inactive = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `AdsenseReportsGenerateResponse` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *reports.generate* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .use_timezone_reporting(false) +/// .start_index(-98) +/// .add_sort("diam") +/// .add_metric("ut") +/// .max_results(-70) +/// .locale("est") +/// .add_filter("amet") +/// .add_dimension("accusam") +/// .currency("clita") +/// .doit(); +/// # } +/// ``` +pub struct AccountReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _start_date: String, + _end_date: String, + _use_timezone_reporting: Option, + _start_index: Option, + _sort: Vec, + _metric: Vec, + _max_results: Option, + _locale: Option, + _filter: Vec, + _dimension: Vec, + _currency: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdsenseReportsGenerateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.reports.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("startDate", self._start_date.to_string())); + params.push(("endDate", self._end_date.to_string())); + if let Some(value) = self._use_timezone_reporting { + params.push(("useTimezoneReporting", value.to_string())); + } + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if self._sort.len() > 0 { + let mut s = String::new(); + for f in self._sort.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sort", s)); + } + if self._metric.len() > 0 { + let mut s = String::new(); + for f in self._metric.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("metric", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if self._dimension.len() > 0 { + let mut s = String::new(); + for f in self._dimension.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dimension", s)); + } + if let Some(value) = self._currency { + params.push(("currency", value.to_string())); + } + for &field in ["accountId", "startDate", "endDate", "useTimezoneReporting", "startIndex", "sort", "metric", "maxResults", "locale", "filter", "dimension", "currency"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account upon which to report. + pub fn account_id(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn start_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn end_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *use timezone reporting* query property to the given value. + /// + /// + /// Whether the report should be generated in the AdSense account's local timezone. If false default PST/PDT timezone will be used. + pub fn use_timezone_reporting(mut self, new_value: bool) -> AccountReportGenerateCall<'a, C, NC, A> { + self._use_timezone_reporting = Some(new_value); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: i32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Append the given value to the *sort* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. + pub fn add_sort(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._sort.push(new_value.to_string()); + self + } + /// Append the given value to the *metric* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Numeric columns to include in the report. + pub fn add_metric(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._metric.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: i32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filters to be run on the report. + pub fn add_filter(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Append the given value to the *dimension* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Dimensions to base the report on. + pub fn add_dimension(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._dimension.push(new_value.to_string()); + self + } + /// Sets the *currency* query property to the given value. + /// + /// + /// Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set. + pub fn currency(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._currency = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad clients in the specified account. +/// +/// A builder for the *adclients.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adclients_list("accountId") +/// .page_token("justo") +/// .max_results(-57) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdclientListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdclientListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdclientListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClients)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.adclients.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to list ad clients. + pub fn account_id(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad clients to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountAdclientListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdclientListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all custom channels in the specified ad client for the specified account. +/// +/// A builder for the *customchannels.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().customchannels_list("accountId", "adClientId") +/// .page_token("ut") +/// .max_results(-19) +/// .doit(); +/// # } +/// ``` +pub struct AccountCustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list custom channels. + pub fn ad_client_id(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all saved ad styles in the specified account. +/// +/// A builder for the *savedadstyles.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().savedadstyles_list("accountId") +/// .page_token("voluptua.") +/// .max_results(-19) +/// .doit(); +/// # } +/// ``` +pub struct AccountSavedadstyleListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountSavedadstyleListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountSavedadstyleListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedAdStyles)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.savedadstyles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/savedadstyles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to list saved ad styles. + pub fn account_id(mut self, new_value: &str) -> AccountSavedadstyleListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through saved ad styles. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountSavedadstyleListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of saved ad styles to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountSavedadstyleListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountSavedadstyleListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountSavedadstyleListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountSavedadstyleListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get ad code for the specified ad unit. +/// +/// A builder for the *adunits.getAdCode* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_get_ad_code("accountId", "adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitGetAdCodeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitGetAdCodeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitGetAdCodeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdCode)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.adunits.getAdCode", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/adcode".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client with contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to get the code for. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all custom channels which the specified ad unit belongs to. +/// +/// A builder for the *adunits.customchannels.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_customchannels_list("accountId", "adClientId", "adUnitId") +/// .page_token("diam") +/// .max_results(-62) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitCustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitCustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitCustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.adunits.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "adUnitId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to which the ad client belongs. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit for which to list custom channels. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitCustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about the selected AdSense account. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get("accountId") +/// .tree(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _account_id: String, + _tree: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._tree { + params.push(("tree", value.to_string())); + } + for &field in ["alt", "accountId", "tree"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to get information about. + pub fn account_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *tree* query property to the given value. + /// + /// + /// Whether the tree of sub accounts should be returned. + pub fn tree(mut self, new_value: bool) -> AccountGetCall<'a, C, NC, A> { + self._tree = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the payments for this AdSense account. +/// +/// A builder for the *list* method supported by a *payment* resource. +/// It is not used directly, but through a `PaymentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.payments().list() +/// .doit(); +/// # } +/// ``` +pub struct PaymentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PaymentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PaymentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Payments)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.payments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/payments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PaymentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PaymentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PaymentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the metadata for the dimensions available to this AdSense account. +/// +/// A builder for the *dimensions.list* method supported by a *metadata* resource. +/// It is not used directly, but through a `MetadataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metadata().dimensions_list() +/// .doit(); +/// # } +/// ``` +pub struct MetadataDimensionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetadataDimensionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetadataDimensionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Metadata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.metadata.dimensions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/metadata/dimensions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetadataDimensionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetadataDimensionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetadataDimensionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the metadata for the metrics available to this AdSense account. +/// +/// A builder for the *metrics.list* method supported by a *metadata* resource. +/// It is not used directly, but through a `MetadataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metadata().metrics_list() +/// .doit(); +/// # } +/// ``` +pub struct MetadataMetricListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetadataMetricListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetadataMetricListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Metadata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.metadata.metrics.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/metadata/metrics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetadataMetricListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetadataMetricListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetadataMetricListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get the specified custom channel from the specified ad client. +/// +/// A builder for the *get* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().get("adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.customchannels.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/customchannels/{customChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to retrieve. + pub fn custom_channel_id(mut self, new_value: &str) -> CustomchannelGetCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all custom channels in the specified ad client for this AdSense account. +/// +/// A builder for the *list* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().list("adClientId") +/// .page_token("eirmod") +/// .max_results(-77) +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list custom channels. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> CustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> CustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad units in the specified custom channel. +/// +/// A builder for the *adunits.list* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsense1d4" as adsense1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsense1d4::AdSense; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSense::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().adunits_list("adClientId", "customChannelId") +/// .page_token("sed") +/// .max_results(-47) +/// .include_inactive(true) +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelAdunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSense, + _ad_client_id: String, + _custom_channel_id: String, + _page_token: Option, + _max_results: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelAdunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelAdunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsense.customchannels.adunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "adClientId", "customChannelId", "pageToken", "maxResults", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsense/v1.4/adclients/{adClientId}/customchannels/{customChannelId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel for which to list ad units. + pub fn custom_channel_id(mut self, new_value: &str) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad units to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include inactive* query property to the given value. + /// + /// + /// Whether to include inactive ad units. Default: true. + pub fn include_inactive(mut self, new_value: bool) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._include_inactive = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelAdunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelAdunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelAdunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/adsensehost4d1/Cargo.toml b/gen/adsensehost4d1/Cargo.toml new file mode 100644 index 0000000000..8078804bff --- /dev/null +++ b/gen/adsensehost4d1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adsensehost4d1" +version = "0.1.0+20150302" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with AdSense Host (protocol v4.1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adsensehost4d1" +homepage = "https://developers.google.com/adsense/host/" +documentation = "http://byron.github.io/google-apis-rs/google-adsensehost4d1" +license = "MIT" +keywords = ["adsensehost", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/adsensehost4d1/LICENSE.md b/gen/adsensehost4d1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adsensehost4d1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/adsensehost4d1/README.md b/gen/adsensehost4d1/README.md new file mode 100644 index 0000000000..b2bf02590d --- /dev/null +++ b/gen/adsensehost4d1/README.md @@ -0,0 +1,191 @@ + +The `google-adsensehost4d1` library allows access to all features of the *Google AdSense Host* service. + +This documentation was generated from *AdSense Host* crate version *0.1.0+20150302*, where *20150302* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *AdSense Host* *v4d1* API can be found at the +[official documentation site](https://developers.google.com/adsense/host/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AdSenseHost.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.Account.html) + * [*adclients get*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdclientGetCall.html), [*adclients list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdclientListCall.html), [*adunits delete*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitDeleteCall.html), [*adunits get*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitGetCall.html), [*adunits get ad code*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitGetAdCodeCall.html), [*adunits insert*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitInsertCall.html), [*adunits list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitListCall.html), [*adunits patch*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitPatchCall.html), [*adunits update*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountAdunitUpdateCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountListCall.html) and [*reports generate*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AccountReportGenerateCall.html) +* adclients + * [*get*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AdclientGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AdclientListCall.html) +* associationsessions + * [*start*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AssociationsessionStartCall.html) and [*verify*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AssociationsessionVerifyCall.html) +* customchannels + * [*delete*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.CustomchannelUpdateCall.html) +* [reports](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.Report.html) + * [*generate*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.ReportGenerateCall.html) +* urlchannels + * [*delete*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.UrlchannelDeleteCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.UrlchannelInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.UrlchannelListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-adsensehost4d1/struct.AdSenseHost.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.accounts().adunits_get(...).doit() +let r = hub.accounts().get(...).doit() +let r = hub.accounts().adunits_list(...).doit() +let r = hub.accounts().adunits_get_ad_code(...).doit() +let r = hub.accounts().reports_generate(...).doit() +let r = hub.accounts().adunits_delete(...).doit() +let r = hub.accounts().adunits_update(...).doit() +let r = hub.accounts().adunits_patch(...).doit() +let r = hub.accounts().adunits_insert(...).doit() +let r = hub.accounts().list(...).doit() +let r = hub.accounts().adclients_list(...).doit() +let r = hub.accounts().adclients_get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-adsensehost4d1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-adsensehost4d1" as adsensehost4d1; +use adsensehost4d1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use adsensehost4d1::AdSenseHost; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") + .start_index(59) + .add_sort("et") + .add_metric("dolores") + .max_results(38) + .locale("accusam") + .add_filter("takimata") + .add_dimension("justo") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-adsensehost4d1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-adsensehost4d1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-adsensehost4d1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-adsensehost4d1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **adsensehost4d1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/adsensehost4d1/src/cmn.rs b/gen/adsensehost4d1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/adsensehost4d1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/adsensehost4d1/src/lib.rs b/gen/adsensehost4d1/src/lib.rs new file mode 100644 index 0000000000..410ddae2d7 --- /dev/null +++ b/gen/adsensehost4d1/src/lib.rs @@ -0,0 +1,8268 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *AdSense Host* crate version *0.1.0+20150302*, where *20150302* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *AdSense Host* *v4d1* API can be found at the +//! [official documentation site](https://developers.google.com/adsense/host/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adsensehost4d1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AdSenseHost.html) ... +//! +//! * [accounts](struct.Account.html) +//! * [*adclients get*](struct.AccountAdclientGetCall.html), [*adclients list*](struct.AccountAdclientListCall.html), [*adunits delete*](struct.AccountAdunitDeleteCall.html), [*adunits get*](struct.AccountAdunitGetCall.html), [*adunits get ad code*](struct.AccountAdunitGetAdCodeCall.html), [*adunits insert*](struct.AccountAdunitInsertCall.html), [*adunits list*](struct.AccountAdunitListCall.html), [*adunits patch*](struct.AccountAdunitPatchCall.html), [*adunits update*](struct.AccountAdunitUpdateCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html) and [*reports generate*](struct.AccountReportGenerateCall.html) +//! * adclients +//! * [*get*](struct.AdclientGetCall.html) and [*list*](struct.AdclientListCall.html) +//! * associationsessions +//! * [*start*](struct.AssociationsessionStartCall.html) and [*verify*](struct.AssociationsessionVerifyCall.html) +//! * customchannels +//! * [*delete*](struct.CustomchannelDeleteCall.html), [*get*](struct.CustomchannelGetCall.html), [*insert*](struct.CustomchannelInsertCall.html), [*list*](struct.CustomchannelListCall.html), [*patch*](struct.CustomchannelPatchCall.html) and [*update*](struct.CustomchannelUpdateCall.html) +//! * [reports](struct.Report.html) +//! * [*generate*](struct.ReportGenerateCall.html) +//! * urlchannels +//! * [*delete*](struct.UrlchannelDeleteCall.html), [*insert*](struct.UrlchannelInsertCall.html) and [*list*](struct.UrlchannelListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AdSenseHost.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.accounts().adunits_get(...).doit() +//! let r = hub.accounts().get(...).doit() +//! let r = hub.accounts().adunits_list(...).doit() +//! let r = hub.accounts().adunits_get_ad_code(...).doit() +//! let r = hub.accounts().reports_generate(...).doit() +//! let r = hub.accounts().adunits_delete(...).doit() +//! let r = hub.accounts().adunits_update(...).doit() +//! let r = hub.accounts().adunits_patch(...).doit() +//! let r = hub.accounts().adunits_insert(...).doit() +//! let r = hub.accounts().list(...).doit() +//! let r = hub.accounts().adclients_list(...).doit() +//! let r = hub.accounts().adclients_get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-adsensehost4d1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-adsensehost4d1" as adsensehost4d1; +//! use adsensehost4d1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use adsensehost4d1::AdSenseHost; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +//! .start_index(92) +//! .add_sort("nonumy") +//! .add_metric("dolores") +//! .max_results(40) +//! .locale("sadipscing") +//! .add_filter("aliquyam") +//! .add_dimension("ea") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your AdSense host data and associated accounts + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/adsensehost", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AdSenseHost related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .start_index(67) +/// .add_sort("et") +/// .add_metric("diam") +/// .max_results(46) +/// .locale("Lorem") +/// .add_filter("et") +/// .add_dimension("duo") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AdSenseHost { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AdSenseHost {} + +impl<'a, C, NC, A> AdSenseHost + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AdSenseHost { + AdSenseHost { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + pub fn adclients(&'a self) -> AdclientMethods<'a, C, NC, A> { + AdclientMethods { hub: &self } + } + pub fn associationsessions(&'a self) -> AssociationsessionMethods<'a, C, NC, A> { + AssociationsessionMethods { hub: &self } + } + pub fn customchannels(&'a self) -> CustomchannelMethods<'a, C, NC, A> { + CustomchannelMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, NC, A> { + ReportMethods { hub: &self } + } + pub fn urlchannels(&'a self) -> UrlchannelMethods<'a, C, NC, A> { + UrlchannelMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list urlchannels](struct.UrlchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlChannels { + /// Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The URL channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsensehost#urlChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for UrlChannels {} + + +/// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportHeaders { + /// The currency of this column. Only present if the header type is METRIC_CURRENCY. + pub currency: String, + /// The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY. + #[serde(alias="type")] + pub type_: String, + /// The name of the header. + pub name: String, +} + +impl NestedType for ReportHeaders {} +impl Part for ReportHeaders {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits get accounts](struct.AccountAdunitGetCall.html) (none) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// * [adunits list accounts](struct.AccountAdunitListCall.html) (none) +/// * [adunits get ad code accounts](struct.AccountAdunitGetAdCodeCall.html) (none) +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (none) +/// * [adunits delete accounts](struct.AccountAdunitDeleteCall.html) (none) +/// * [adunits update accounts](struct.AccountAdunitUpdateCall.html) (none) +/// * [adunits patch accounts](struct.AccountAdunitPatchCall.html) (none) +/// * [adunits insert accounts](struct.AccountAdunitInsertCall.html) (none) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (none) +/// * [adclients get accounts](struct.AccountAdclientGetCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Account { + /// Approval status of this account. One of: PENDING, APPROVED, DISABLED. + pub status: String, + /// Kind of resource this is, in this case adsensehost#account. + pub kind: String, + /// Unique identifier of this account. + pub id: String, + /// Name of this account. + pub name: String, +} + +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits list accounts](struct.AccountAdunitListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdUnits { + /// Continuation token used to page through ad units. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The ad units returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsensehost#adUnits. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for AdUnits {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list adclients](struct.AdclientListCall.html) (response) +/// * [adclients list accounts](struct.AccountAdclientListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClients { + /// Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The ad clients returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsensehost#adClients. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for AdClients {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdStyle { + /// The style of the corners in the ad. Possible values are SQUARE, SLIGHTLY_ROUNDED and VERY_ROUNDED. + pub corners: String, + /// The colors included in the style. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading hash. + pub colors: AdStyleColors, + /// The font which is included in the style. + pub font: AdStyleFont, + /// Kind this is, in this case adsensehost#adStyle. + pub kind: String, +} + +impl Part for AdStyle {} + + +/// The colors included in the style. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading hash. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdStyleColors { + /// The color of the ad url. + pub url: String, + /// The color of the ad text. + pub text: String, + /// The color of the ad border. + pub border: String, + /// The color of the ad background. + pub background: String, + /// The color of the ad title. + pub title: String, +} + +impl NestedType for AdStyleColors {} +impl Part for AdStyleColors {} + + +/// Settings specific to WAP mobile content ads (AFMC). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdUnitMobileContentAdsSettings { + /// The scripting language to use for this ad unit. + #[serde(alias="scriptingLanguage")] + pub scripting_language: String, + /// The markup language to use for this ad unit. + #[serde(alias="markupLanguage")] + pub markup_language: String, + /// Type of this ad unit. + #[serde(alias="type")] + pub type_: String, + /// Size of this ad unit. + pub size: String, +} + +impl NestedType for AdUnitMobileContentAdsSettings {} +impl Part for AdUnitMobileContentAdsSettings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits get ad code accounts](struct.AccountAdunitGetAdCodeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdCode { + /// The ad code snippet. + #[serde(alias="adCode")] + pub ad_code: String, + /// Kind this is, in this case adsensehost#adCode. + pub kind: String, +} + +impl ResponseResult for AdCode {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [adunits get accounts](struct.AccountAdunitGetCall.html) (response) +/// * [adunits patch accounts](struct.AccountAdunitPatchCall.html) (request|response) +/// * [adunits update accounts](struct.AccountAdunitUpdateCall.html) (request|response) +/// * [adunits delete accounts](struct.AccountAdunitDeleteCall.html) (response) +/// * [adunits insert accounts](struct.AccountAdunitInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdUnit { + /// Status of this ad unit. Possible values are: + /// NEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it. + /// + /// ACTIVE: Indicates that there has been activity on this ad unit in the last seven days. + /// + /// INACTIVE: Indicates that there has been no activity on this ad unit in the last seven days. + pub status: Option, + /// Kind of resource this is, in this case adsensehost#adUnit. + pub kind: Option, + /// Identity code of this ad unit, not necessarily unique across ad clients. + pub code: Option, + /// Name of this ad unit. + pub name: Option, + /// Settings specific to content ads (AFC) and highend mobile content ads (AFMC). + #[serde(alias="contentAdsSettings")] + pub content_ads_settings: Option, + /// Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: Option, + /// Settings specific to WAP mobile content ads (AFMC). + #[serde(alias="mobileContentAdsSettings")] + pub mobile_content_ads_settings: Option, + /// Custom style information specific to this ad unit. + #[serde(alias="customStyle")] + pub custom_style: Option, +} + +impl RequestValue for AdUnit {} +impl ResponseResult for AdUnit {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete urlchannels](struct.UrlchannelDeleteCall.html) (response) +/// * [insert urlchannels](struct.UrlchannelInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UrlChannel { + /// Kind of resource this is, in this case adsensehost#urlChannel. + pub kind: Option, + /// Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: Option, + /// URL Pattern of this URL channel. Does not include "http://" or "https://". Example: www.example.com/home + #[serde(alias="urlPattern")] + pub url_pattern: Option, +} + +impl RequestValue for UrlChannel {} +impl Resource for UrlChannel {} +impl ResponseResult for UrlChannel {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get adclients](struct.AdclientGetCall.html) (response) +/// * [adclients get accounts](struct.AccountAdclientGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdClient { + /// This ad client's product code, which corresponds to the PRODUCT_CODE report dimension. + #[serde(alias="productCode")] + pub product_code: String, + /// Kind of resource this is, in this case adsensehost#adClient. + pub kind: String, + /// Unique identifier of this ad client. + pub id: String, + /// Whether this ad client is opted in to ARC. + #[serde(alias="arcOptIn")] + pub arc_opt_in: bool, + /// Whether this ad client supports being reported on. + #[serde(alias="supportsReporting")] + pub supports_reporting: bool, +} + +impl Resource for AdClient {} +impl ResponseResult for AdClient {} + + +/// The backup option to be used in instances where no ad is available. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdUnitContentAdsSettingsBackupOption { + /// Color to use when type is set to COLOR. These are represented as six hexadecimal characters, similar to HTML color codes, but without the leading hash. + pub color: String, + /// URL to use when type is set to URL. + pub url: String, + /// Type of the backup option. Possible values are BLANK, COLOR and URL. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for AdUnitContentAdsSettingsBackupOption {} +impl Part for AdUnitContentAdsSettingsBackupOption {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [verify associationsessions](struct.AssociationsessionVerifyCall.html) (response) +/// * [start associationsessions](struct.AssociationsessionStartCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AssociationSession { + /// Status of the completed association, available once the association callback token has been verified. One of ACCEPTED, REJECTED, or ERROR. + pub status: String, + /// The products to associate with the user. Options: AFC, AFF, AFS, AFMC + #[serde(alias="productCodes")] + pub product_codes: Vec, + /// Kind of resource this is, in this case adsensehost#associationSession. + pub kind: String, + /// The preferred locale of the user themselves when going through the AdSense association flow. + #[serde(alias="userLocale")] + pub user_locale: String, + /// The locale of the user's hosted website. + #[serde(alias="websiteLocale")] + pub website_locale: String, + /// Redirect URL of this association session. Used to redirect users into the AdSense association flow. + #[serde(alias="redirectUrl")] + pub redirect_url: String, + /// The URL of the user's hosted website. + #[serde(alias="websiteUrl")] + pub website_url: String, + /// Unique identifier of this association session. + pub id: String, + /// Hosted account id of the associated publisher after association. Present if status is ACCEPTED. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl Resource for AssociationSession {} +impl ResponseResult for AssociationSession {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Accounts { + /// The accounts returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsensehost#accounts. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for Accounts {} + + +/// Settings specific to content ads (AFC) and highend mobile content ads (AFMC). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdUnitContentAdsSettings { + /// Type of this ad unit. Possible values are TEXT, TEXT_IMAGE, IMAGE and LINK. + #[serde(alias="type")] + pub type_: String, + /// The backup option to be used in instances where no ad is available. + #[serde(alias="backupOption")] + pub backup_option: AdUnitContentAdsSettingsBackupOption, + /// Size of this ad unit. Size values are in the form SIZE_{width}_{height}. + pub size: String, +} + +impl NestedType for AdUnitContentAdsSettings {} +impl Part for AdUnitContentAdsSettings {} + + +/// The font which is included in the style. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdStyleFont { + /// The family of the font. Possible values are: ACCOUNT_DEFAULT_FAMILY, ADSENSE_DEFAULT_FAMILY, ARIAL, TIMES and VERDANA. + pub family: String, + /// The size of the font. Possible values are: ACCOUNT_DEFAULT_SIZE, ADSENSE_DEFAULT_SIZE, SMALL, MEDIUM and LARGE. + pub size: String, +} + +impl NestedType for AdStyleFont {} +impl Part for AdStyleFont {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [reports generate accounts](struct.AccountReportGenerateCall.html) (response) +/// * [generate reports](struct.ReportGenerateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Report { + /// The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request. + pub headers: Vec, + /// Kind this is, in this case adsensehost#report. + pub kind: String, + /// The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The dimension cells contain strings, and the metric cells contain numbers. + pub rows: Vec>, + /// The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or the report row limit. + #[serde(alias="totalMatchedRows")] + pub total_matched_rows: String, + /// Any warnings associated with generation of the report. + pub warnings: Vec, + /// The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub averages: Vec, + /// The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty. + pub totals: Vec, +} + +impl Resource for Report {} +impl ResponseResult for Report {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get customchannels](struct.CustomchannelGetCall.html) (response) +/// * [update customchannels](struct.CustomchannelUpdateCall.html) (request|response) +/// * [delete customchannels](struct.CustomchannelDeleteCall.html) (response) +/// * [insert customchannels](struct.CustomchannelInsertCall.html) (request|response) +/// * [patch customchannels](struct.CustomchannelPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomChannel { + /// Kind of resource this is, in this case adsensehost#customChannel. + pub kind: Option, + /// Code of this custom channel, not necessarily unique across ad clients. + pub code: Option, + /// Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format. + pub id: Option, + /// Name of this custom channel. + pub name: Option, +} + +impl RequestValue for CustomChannel {} +impl Resource for CustomChannel {} +impl ResponseResult for CustomChannel {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list customchannels](struct.CustomchannelListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomChannels { + /// Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's "pageToken" value to this. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The custom channels returned in this list response. + pub items: Vec, + /// Kind of list this is, in this case adsensehost#customChannels. + pub kind: String, + /// ETag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for CustomChannels {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *urlchannel* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.urlchannels(); +/// # } +/// ``` +pub struct UrlchannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UrlchannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Add a new URL channel to the host AdSense account. + pub fn insert(&self, request: &UrlChannel, ad_client_id: &str) -> UrlchannelInsertCall<'a, C, NC, A> { + UrlchannelInsertCall { + hub: self.hub, + _request: request.clone(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a URL channel from the host AdSense account. + pub fn delete(&self, ad_client_id: &str, url_channel_id: &str) -> UrlchannelDeleteCall<'a, C, NC, A> { + UrlchannelDeleteCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _url_channel_id: url_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all host URL channels in the host AdSense account. + pub fn list(&self, ad_client_id: &str) -> UrlchannelListCall<'a, C, NC, A> { + UrlchannelListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *adclient* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.adclients(); +/// # } +/// ``` +pub struct AdclientMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdclientMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdclientMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all host ad clients in this AdSense account. + pub fn list(&self) -> AdclientListCall<'a, C, NC, A> { + AdclientListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about one of the ad clients in the Host AdSense account. + pub fn get(&self, ad_client_id: &str) -> AdclientGetCall<'a, C, NC, A> { + AdclientGetCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *associationsession* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `start(...)` and `verify(...)` +/// // to build up your call. +/// let rb = hub.associationsessions(); +/// # } +/// ``` +pub struct AssociationsessionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AssociationsessionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AssociationsessionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Create an association session for initiating an association with an AdSense user. + pub fn start(&self, product_code: &Vec, website_url: &str) -> AssociationsessionStartCall<'a, C, NC, A> { + AssociationsessionStartCall { + hub: self.hub, + _product_code: product_code.clone(), + _website_url: website_url.to_string(), + _website_locale: Default::default(), + _user_locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Verify an association session after the association callback returns from AdSense signup. + pub fn verify(&self, token: &str) -> AssociationsessionVerifyCall<'a, C, NC, A> { + AssociationsessionVerifyCall { + hub: self.hub, + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *report* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generate(...)` +/// // to build up your call. +/// let rb = hub.reports(); +/// # } +/// ``` +pub struct ReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. + pub fn generate(&self, start_date: &str, end_date: &str) -> ReportGenerateCall<'a, C, NC, A> { + ReportGenerateCall { + hub: self.hub, + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _start_index: Default::default(), + _sort: Default::default(), + _metric: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _filter: Default::default(), + _dimension: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `adclients_get(...)`, `adclients_list(...)`, `adunits_delete(...)`, `adunits_get(...)`, `adunits_get_ad_code(...)`, `adunits_insert(...)`, `adunits_list(...)`, `adunits_patch(...)`, `adunits_update(...)`, `get(...)`, `list(...)` and `reports_generate(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List all ad units in the specified publisher's AdSense account. + pub fn adunits_list(&self, account_id: &str, ad_client_id: &str) -> AccountAdunitListCall<'a, C, NC, A> { + AccountAdunitListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_inactive: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List hosted accounts associated with this AdSense account by ad client id. + pub fn list(&self, filter_ad_client_id: &Vec) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _filter_ad_client_id: filter_ad_client_id.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get ad code for the specified ad unit, attaching the specified host custom channels. + pub fn adunits_get_ad_code(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + AccountAdunitGetAdCodeCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _host_custom_channel_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. + pub fn reports_generate(&self, account_id: &str, start_date: &str, end_date: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + AccountReportGenerateCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _start_index: Default::default(), + _sort: Default::default(), + _metric: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _filter: Default::default(), + _dimension: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete the specified ad unit from the specified publisher AdSense account. + pub fn adunits_delete(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitDeleteCall<'a, C, NC, A> { + AccountAdunitDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all hosted ad clients in the specified hosted account. + pub fn adclients_list(&self, account_id: &str) -> AccountAdclientListCall<'a, C, NC, A> { + AccountAdclientListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the supplied ad unit in the specified publisher AdSense account. This method supports patch semantics. + pub fn adunits_patch(&self, request: &AdUnit, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitPatchCall<'a, C, NC, A> { + AccountAdunitPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about one of the ad clients in the specified publisher's AdSense account. + pub fn adclients_get(&self, account_id: &str, ad_client_id: &str) -> AccountAdclientGetCall<'a, C, NC, A> { + AccountAdclientGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get information about the selected associated AdSense account. + pub fn get(&self, account_id: &str) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Insert the supplied ad unit into the specified publisher AdSense account. + pub fn adunits_insert(&self, request: &AdUnit, account_id: &str, ad_client_id: &str) -> AccountAdunitInsertCall<'a, C, NC, A> { + AccountAdunitInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get the specified host ad unit in this AdSense account. + pub fn adunits_get(&self, account_id: &str, ad_client_id: &str, ad_unit_id: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + AccountAdunitGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _ad_unit_id: ad_unit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the supplied ad unit in the specified publisher AdSense account. + pub fn adunits_update(&self, request: &AdUnit, account_id: &str, ad_client_id: &str) -> AccountAdunitUpdateCall<'a, C, NC, A> { + AccountAdunitUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *customchannel* resources. +/// It is not used directly, but through the `AdSenseHost` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-adsensehost4d1" as adsensehost4d1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adsensehost4d1::AdSenseHost; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.customchannels(); +/// # } +/// ``` +pub struct CustomchannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CustomchannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Get a specific custom channel from the host AdSense account. + pub fn get(&self, ad_client_id: &str, custom_channel_id: &str) -> CustomchannelGetCall<'a, C, NC, A> { + CustomchannelGetCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a specific custom channel from the host AdSense account. + pub fn delete(&self, ad_client_id: &str, custom_channel_id: &str) -> CustomchannelDeleteCall<'a, C, NC, A> { + CustomchannelDeleteCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update a custom channel in the host AdSense account. + pub fn update(&self, request: &CustomChannel, ad_client_id: &str) -> CustomchannelUpdateCall<'a, C, NC, A> { + CustomchannelUpdateCall { + hub: self.hub, + _request: request.clone(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all host custom channels in this AdSense account. + pub fn list(&self, ad_client_id: &str) -> CustomchannelListCall<'a, C, NC, A> { + CustomchannelListCall { + hub: self.hub, + _ad_client_id: ad_client_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update a custom channel in the host AdSense account. This method supports patch semantics. + pub fn patch(&self, request: &CustomChannel, ad_client_id: &str, custom_channel_id: &str) -> CustomchannelPatchCall<'a, C, NC, A> { + CustomchannelPatchCall { + hub: self.hub, + _request: request.clone(), + _ad_client_id: ad_client_id.to_string(), + _custom_channel_id: custom_channel_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a new custom channel to the host AdSense account. + pub fn insert(&self, request: &CustomChannel, ad_client_id: &str) -> CustomchannelInsertCall<'a, C, NC, A> { + CustomchannelInsertCall { + hub: self.hub, + _request: request.clone(), + _ad_client_id: ad_client_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Add a new URL channel to the host AdSense account. +/// +/// A builder for the *insert* method supported by a *urlchannel* resource. +/// It is not used directly, but through a `UrlchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::UrlChannel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlChannel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.urlchannels().insert(&req, "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct UrlchannelInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: UrlChannel, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlchannelInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.urlchannels.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/urlchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlChannel) -> UrlchannelInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client to which the new URL channel will be added. + pub fn ad_client_id(mut self, new_value: &str) -> UrlchannelInsertCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlchannelInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlchannelInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlchannelInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a URL channel from the host AdSense account. +/// +/// A builder for the *delete* method supported by a *urlchannel* resource. +/// It is not used directly, but through a `UrlchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.urlchannels().delete("adClientId", "urlChannelId") +/// .doit(); +/// # } +/// ``` +pub struct UrlchannelDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _url_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlchannelDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.urlchannels.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("urlChannelId", self._url_channel_id.to_string())); + for &field in ["alt", "adClientId", "urlChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/urlchannels/{urlChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{urlChannelId}", "urlChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "urlChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client from which to delete the URL channel. + pub fn ad_client_id(mut self, new_value: &str) -> UrlchannelDeleteCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *url channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// URL channel to delete. + pub fn url_channel_id(mut self, new_value: &str) -> UrlchannelDeleteCall<'a, C, NC, A> { + self._url_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlchannelDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlchannelDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlchannelDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all host URL channels in the host AdSense account. +/// +/// A builder for the *list* method supported by a *urlchannel* resource. +/// It is not used directly, but through a `UrlchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.urlchannels().list("adClientId") +/// .page_token("erat") +/// .max_results(6) +/// .doit(); +/// # } +/// ``` +pub struct UrlchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.urlchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/urlchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list URL channels. + pub fn ad_client_id(mut self, new_value: &str) -> UrlchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> UrlchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of URL channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> UrlchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all host ad clients in this AdSense account. +/// +/// A builder for the *list* method supported by a *adclient* resource. +/// It is not used directly, but through a `AdclientMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adclients().list() +/// .page_token("dolor") +/// .max_results(62) +/// .doit(); +/// # } +/// ``` +pub struct AdclientListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdclientListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdclientListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClients)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.adclients.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AdclientListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad clients to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AdclientListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdclientListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdclientListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdclientListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about one of the ad clients in the Host AdSense account. +/// +/// A builder for the *get* method supported by a *adclient* resource. +/// It is not used directly, but through a `AdclientMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.adclients().get("adClientId") +/// .doit(); +/// # } +/// ``` +pub struct AdclientGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdclientGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdclientGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClient)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.adclients.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client to get. + pub fn ad_client_id(mut self, new_value: &str) -> AdclientGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdclientGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdclientGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdclientGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create an association session for initiating an association with an AdSense user. +/// +/// A builder for the *start* method supported by a *associationsession* resource. +/// It is not used directly, but through a `AssociationsessionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.associationsessions().start("productCode", "websiteUrl") +/// .website_locale("labore") +/// .user_locale("eirmod") +/// .doit(); +/// # } +/// ``` +pub struct AssociationsessionStartCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _product_code: Vec, + _website_url: String, + _website_locale: Option, + _user_locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AssociationsessionStartCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AssociationsessionStartCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AssociationSession)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.associationsessions.start", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if self._product_code.len() > 0 { + let mut s = String::new(); + for f in self._product_code.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("productCode", s)); + } + params.push(("websiteUrl", self._website_url.to_string())); + if let Some(value) = self._website_locale { + params.push(("websiteLocale", value.to_string())); + } + if let Some(value) = self._user_locale { + params.push(("userLocale", value.to_string())); + } + for &field in ["alt", "productCode", "websiteUrl", "websiteLocale", "userLocale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/associationsessions/start".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *product code* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Products to associate with the user. + pub fn add_product_code(mut self, new_value: &str) -> AssociationsessionStartCall<'a, C, NC, A> { + self._product_code.push(new_value.to_string()); + self + } + /// Sets the *website url* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The URL of the user's hosted website. + pub fn website_url(mut self, new_value: &str) -> AssociationsessionStartCall<'a, C, NC, A> { + self._website_url = new_value.to_string(); + self + } + /// Sets the *website locale* query property to the given value. + /// + /// + /// The locale of the user's hosted website. + pub fn website_locale(mut self, new_value: &str) -> AssociationsessionStartCall<'a, C, NC, A> { + self._website_locale = Some(new_value.to_string()); + self + } + /// Sets the *user locale* query property to the given value. + /// + /// + /// The preferred locale of the user. + pub fn user_locale(mut self, new_value: &str) -> AssociationsessionStartCall<'a, C, NC, A> { + self._user_locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AssociationsessionStartCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AssociationsessionStartCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AssociationsessionStartCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Verify an association session after the association callback returns from AdSense signup. +/// +/// A builder for the *verify* method supported by a *associationsession* resource. +/// It is not used directly, but through a `AssociationsessionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.associationsessions().verify("token") +/// .doit(); +/// # } +/// ``` +pub struct AssociationsessionVerifyCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AssociationsessionVerifyCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AssociationsessionVerifyCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AssociationSession)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.associationsessions.verify", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/associationsessions/verify".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *token* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token returned to the association callback URL. + pub fn token(mut self, new_value: &str) -> AssociationsessionVerifyCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AssociationsessionVerifyCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AssociationsessionVerifyCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AssociationsessionVerifyCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. +/// +/// A builder for the *generate* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().generate("startDate", "endDate") +/// .start_index(28) +/// .add_sort("Lorem") +/// .add_metric("sea") +/// .max_results(80) +/// .locale("duo") +/// .add_filter("et") +/// .add_dimension("eirmod") +/// .doit(); +/// # } +/// ``` +pub struct ReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _start_date: String, + _end_date: String, + _start_index: Option, + _sort: Vec, + _metric: Vec, + _max_results: Option, + _locale: Option, + _filter: Vec, + _dimension: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.reports.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("startDate", self._start_date.to_string())); + params.push(("endDate", self._end_date.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if self._sort.len() > 0 { + let mut s = String::new(); + for f in self._sort.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sort", s)); + } + if self._metric.len() > 0 { + let mut s = String::new(); + for f in self._metric.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("metric", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if self._dimension.len() > 0 { + let mut s = String::new(); + for f in self._dimension.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dimension", s)); + } + for &field in ["alt", "startDate", "endDate", "startIndex", "sort", "metric", "maxResults", "locale", "filter", "dimension"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn start_date(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn end_date(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: u32) -> ReportGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Append the given value to the *sort* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. + pub fn add_sort(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._sort.push(new_value.to_string()); + self + } + /// Append the given value to the *metric* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Numeric columns to include in the report. + pub fn add_metric(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._metric.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: u32) -> ReportGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filters to be run on the report. + pub fn add_filter(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Append the given value to the *dimension* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Dimensions to base the report on. + pub fn add_dimension(mut self, new_value: &str) -> ReportGenerateCall<'a, C, NC, A> { + self._dimension.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all ad units in the specified publisher's AdSense account. +/// +/// A builder for the *adunits.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_list("accountId", "adClientId") +/// .page_token("amet") +/// .max_results(78) +/// .include_inactive(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnits)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "accountId", "adClientId", "pageToken", "maxResults", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list ad units. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdunitListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad units to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountAdunitListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include inactive* query property to the given value. + /// + /// + /// Whether to include inactive ad units. Default: true. + pub fn include_inactive(mut self, new_value: bool) -> AccountAdunitListCall<'a, C, NC, A> { + self._include_inactive = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List hosted accounts associated with this AdSense account by ad client id. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list("filterAdClientId") +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _filter_ad_client_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Accounts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + if self._filter_ad_client_id.len() > 0 { + let mut s = String::new(); + for f in self._filter_ad_client_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filterAdClientId", s)); + } + for &field in ["alt", "filterAdClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *filter ad client id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad clients to list accounts for. + pub fn add_filter_ad_client_id(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._filter_ad_client_id.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get ad code for the specified ad unit, attaching the specified host custom channels. +/// +/// A builder for the *adunits.getAdCode* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_get_ad_code("accountId", "adClientId", "adUnitId") +/// .add_host_custom_channel_id("dolor") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitGetAdCodeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _host_custom_channel_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitGetAdCodeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitGetAdCodeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdCode)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.getAdCode", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + if self._host_custom_channel_id.len() > 0 { + let mut s = String::new(); + for f in self._host_custom_channel_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("hostCustomChannelId", s)); + } + for &field in ["alt", "accountId", "adClientId", "adUnitId", "hostCustomChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/adcode".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client with contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to get the code for. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Append the given value to the *host custom channel id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Host custom channel to attach to the ad code. + pub fn add_host_custom_channel_id(mut self, new_value: &str) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._host_custom_channel_id.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitGetAdCodeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter. +/// +/// A builder for the *reports.generate* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().reports_generate("accountId", "startDate", "endDate") +/// .start_index(49) +/// .add_sort("voluptua.") +/// .add_metric("Lorem") +/// .max_results(90) +/// .locale("justo") +/// .add_filter("sit") +/// .add_dimension("vero") +/// .doit(); +/// # } +/// ``` +pub struct AccountReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _start_date: String, + _end_date: String, + _start_index: Option, + _sort: Vec, + _metric: Vec, + _max_results: Option, + _locale: Option, + _filter: Vec, + _dimension: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.reports.generate", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("startDate", self._start_date.to_string())); + params.push(("endDate", self._end_date.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if self._sort.len() > 0 { + let mut s = String::new(); + for f in self._sort.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sort", s)); + } + if self._metric.len() > 0 { + let mut s = String::new(); + for f in self._metric.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("metric", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if self._dimension.len() > 0 { + let mut s = String::new(); + for f in self._dimension.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dimension", s)); + } + for &field in ["alt", "accountId", "startDate", "endDate", "startIndex", "sort", "metric", "maxResults", "locale", "filter", "dimension"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Hosted account upon which to report. + pub fn account_id(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn start_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the date range to report on in "YYYY-MM-DD" format, inclusive. + pub fn end_date(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first row of report data to return. + pub fn start_index(mut self, new_value: u32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Append the given value to the *sort* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending. + pub fn add_sort(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._sort.push(new_value.to_string()); + self + } + /// Append the given value to the *metric* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Numeric columns to include in the report. + pub fn add_metric(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._metric.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of rows of report data to return. + pub fn max_results(mut self, new_value: u32) -> AccountReportGenerateCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified. + pub fn locale(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filters to be run on the report. + pub fn add_filter(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Append the given value to the *dimension* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Dimensions to base the report on. + pub fn add_dimension(mut self, new_value: &str) -> AccountReportGenerateCall<'a, C, NC, A> { + self._dimension.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete the specified ad unit from the specified publisher AdSense account. +/// +/// A builder for the *adunits.delete* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_delete("accountId", "adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad unit. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to get ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitDeleteCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to delete. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitDeleteCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all hosted ad clients in the specified hosted account. +/// +/// A builder for the *adclients.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adclients_list("accountId") +/// .page_token("vero") +/// .max_results(6) +/// .doit(); +/// # } +/// ``` +pub struct AccountAdclientListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdclientListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdclientListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClients)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adclients.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "accountId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account for which to list ad clients. + pub fn account_id(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> AccountAdclientListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of ad clients to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountAdclientListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdclientListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdclientListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the supplied ad unit in the specified publisher AdSense account. This method supports patch semantics. +/// +/// A builder for the *adunits.patch* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::AdUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_patch(&req, "accountId", "adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: AdUnit, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdUnit) -> AccountAdunitPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitPatchCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to get. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitPatchCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about one of the ad clients in the specified publisher's AdSense account. +/// +/// A builder for the *adclients.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adclients_get("accountId", "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdclientGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdclientGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdclientGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdClient)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adclients.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "accountId", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdclientGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client to get. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdclientGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdclientGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdclientGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdclientGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get information about the selected associated AdSense account. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get("accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account to get information about. + pub fn account_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Insert the supplied ad unit into the specified publisher AdSense account. +/// +/// A builder for the *adunits.insert* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::AdUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_insert(&req, "accountId", "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: AdUnit, + _account_id: String, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "accountId", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdUnit) -> AccountAdunitInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which will contain the ad unit. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client into which to insert the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitInsertCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get the specified host ad unit in this AdSense account. +/// +/// A builder for the *adunits.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_get("accountId", "adClientId", "adUnitId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _account_id: String, + _ad_client_id: String, + _ad_unit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("adUnitId", self._ad_unit_id.to_string())); + for &field in ["alt", "accountId", "adClientId", "adUnitId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId"), ("{adUnitId}", "adUnitId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "adClientId", "adUnitId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad unit. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to get ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *ad unit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad unit to get. + pub fn ad_unit_id(mut self, new_value: &str) -> AccountAdunitGetCall<'a, C, NC, A> { + self._ad_unit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the supplied ad unit in the specified publisher AdSense account. +/// +/// A builder for the *adunits.update* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::AdUnit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdUnit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().adunits_update(&req, "accountId", "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct AccountAdunitUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: AdUnit, + _account_id: String, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAdunitUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAdunitUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdUnit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.accounts.adunits.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "accountId", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/accounts/{accountId}/adclients/{adClientId}/adunits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdUnit) -> AccountAdunitUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account which contains the ad client. + pub fn account_id(mut self, new_value: &str) -> AccountAdunitUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client which contains the ad unit. + pub fn ad_client_id(mut self, new_value: &str) -> AccountAdunitUpdateCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAdunitUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAdunitUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAdunitUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get a specific custom channel from the host AdSense account. +/// +/// A builder for the *get* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().get("adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels/{customChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client from which to get the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelGetCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to get. + pub fn custom_channel_id(mut self, new_value: &str) -> CustomchannelGetCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a specific custom channel from the host AdSense account. +/// +/// A builder for the *delete* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().delete("adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels/{customChannelId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId"), ("{customChannelId}", "customChannelId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["adClientId", "customChannelId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client from which to delete the custom channel. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelDeleteCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to delete. + pub fn custom_channel_id(mut self, new_value: &str) -> CustomchannelDeleteCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a custom channel in the host AdSense account. +/// +/// A builder for the *update* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::CustomChannel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomChannel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().update(&req, "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: CustomChannel, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomChannel) -> CustomchannelUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client in which the custom channel will be updated. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelUpdateCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all host custom channels in this AdSense account. +/// +/// A builder for the *list* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().list("adClientId") +/// .page_token("rebum.") +/// .max_results(68) +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _ad_client_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannels)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "adClientId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client for which to list custom channels. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelListCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> CustomchannelListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of custom channels to include in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> CustomchannelListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a custom channel in the host AdSense account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::CustomChannel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomChannel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().patch(&req, "adClientId", "customChannelId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: CustomChannel, + _ad_client_id: String, + _custom_channel_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + params.push(("customChannelId", self._custom_channel_id.to_string())); + for &field in ["alt", "adClientId", "customChannelId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomChannel) -> CustomchannelPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client in which the custom channel will be updated. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelPatchCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *custom channel id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom channel to get. + pub fn custom_channel_id(mut self, new_value: &str) -> CustomchannelPatchCall<'a, C, NC, A> { + self._custom_channel_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a new custom channel to the host AdSense account. +/// +/// A builder for the *insert* method supported by a *customchannel* resource. +/// It is not used directly, but through a `CustomchannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-adsensehost4d1" as adsensehost4d1; +/// use adsensehost4d1::CustomChannel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adsensehost4d1::AdSenseHost; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AdSenseHost::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomChannel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customchannels().insert(&req, "adClientId") +/// .doit(); +/// # } +/// ``` +pub struct CustomchannelInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AdSenseHost, + _request: CustomChannel, + _ad_client_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomchannelInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomchannelInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomChannel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "adsensehost.customchannels.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("adClientId", self._ad_client_id.to_string())); + for &field in ["alt", "adClientId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/adsensehost/v4.1/adclients/{adClientId}/customchannels".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{adClientId}", "adClientId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["adClientId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomChannel) -> CustomchannelInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *ad client id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad client to which the new custom channel will be added. + pub fn ad_client_id(mut self, new_value: &str) -> CustomchannelInsertCall<'a, C, NC, A> { + self._ad_client_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomchannelInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomchannelInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomchannelInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/analytics3/Cargo.toml b/gen/analytics3/Cargo.toml new file mode 100644 index 0000000000..bee1c78383 --- /dev/null +++ b/gen/analytics3/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-analytics3" +version = "0.1.0+20150308" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with analytics (protocol v3)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/analytics3" +homepage = "https://developers.google.com/analytics/" +documentation = "http://byron.github.io/google-apis-rs/google-analytics3" +license = "MIT" +keywords = ["analytics", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/analytics3/LICENSE.md b/gen/analytics3/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/analytics3/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/analytics3/README.md b/gen/analytics3/README.md new file mode 100644 index 0000000000..37fdd2414b --- /dev/null +++ b/gen/analytics3/README.md @@ -0,0 +1,184 @@ + +The `google-analytics3` library allows access to all features of the *Google analytics* service. + +This documentation was generated from *analytics* crate version *0.1.0+20150308*, where *20150308* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *analytics* *v3* API can be found at the +[official documentation site](https://developers.google.com/analytics/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-analytics3/struct.Analytics.html) ... + +* data + * [*ga get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.DataGaGetCall.html), [*mcf get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.DataMcfGetCall.html) and [*realtime get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.DataRealtimeGetCall.html) +* management + * [*account summaries list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountSummaryListCall.html), [*account user links delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountUserLinkDeleteCall.html), [*account user links insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountUserLinkInsertCall.html), [*account user links list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountUserLinkListCall.html), [*account user links update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountUserLinkUpdateCall.html), [*accounts list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementAccountListCall.html), [*custom data sources list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDataSourceListCall.html), [*custom dimensions get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDimensionGetCall.html), [*custom dimensions insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDimensionInsertCall.html), [*custom dimensions list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDimensionListCall.html), [*custom dimensions patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDimensionPatchCall.html), [*custom dimensions update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomDimensionUpdateCall.html), [*custom metrics get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomMetricGetCall.html), [*custom metrics insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomMetricInsertCall.html), [*custom metrics list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomMetricListCall.html), [*custom metrics patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomMetricPatchCall.html), [*custom metrics update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementCustomMetricUpdateCall.html), [*experiments delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentDeleteCall.html), [*experiments get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentGetCall.html), [*experiments insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentInsertCall.html), [*experiments list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentListCall.html), [*experiments patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentPatchCall.html), [*experiments update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementExperimentUpdateCall.html), [*filters delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterDeleteCall.html), [*filters get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterGetCall.html), [*filters insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterInsertCall.html), [*filters list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterListCall.html), [*filters patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterPatchCall.html), [*filters update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementFilterUpdateCall.html), [*goals get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementGoalGetCall.html), [*goals insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementGoalInsertCall.html), [*goals list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementGoalListCall.html), [*goals patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementGoalPatchCall.html), [*goals update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementGoalUpdateCall.html), [*profile filter links delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkDeleteCall.html), [*profile filter links get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkGetCall.html), [*profile filter links insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkInsertCall.html), [*profile filter links list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkListCall.html), [*profile filter links patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkPatchCall.html), [*profile filter links update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileFilterLinkUpdateCall.html), [*profile user links delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileUserLinkDeleteCall.html), [*profile user links insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileUserLinkInsertCall.html), [*profile user links list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileUserLinkListCall.html), [*profile user links update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileUserLinkUpdateCall.html), [*profiles delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileDeleteCall.html), [*profiles get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileGetCall.html), [*profiles insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileInsertCall.html), [*profiles list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileListCall.html), [*profiles patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfilePatchCall.html), [*profiles update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementProfileUpdateCall.html), [*segments list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementSegmentListCall.html), [*unsampled reports get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUnsampledReportGetCall.html), [*unsampled reports insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUnsampledReportInsertCall.html), [*unsampled reports list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUnsampledReportListCall.html), [*uploads delete upload data*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUploadDeleteUploadDataCall.html), [*uploads get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUploadGetCall.html), [*uploads list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUploadListCall.html), [*uploads upload data*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUploadUploadDataCall.html), [*web property ad words links delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkDeleteCall.html), [*web property ad words links get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkGetCall.html), [*web property ad words links insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkInsertCall.html), [*web property ad words links list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkListCall.html), [*web property ad words links patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkPatchCall.html), [*web property ad words links update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebPropertyAdWordsLinkUpdateCall.html), [*webproperties get*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyGetCall.html), [*webproperties insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyInsertCall.html), [*webproperties list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyListCall.html), [*webproperties patch*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyPatchCall.html), [*webproperties update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyUpdateCall.html), [*webproperty user links delete*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyUserLinkDeleteCall.html), [*webproperty user links insert*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyUserLinkInsertCall.html), [*webproperty user links list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyUserLinkListCall.html) and [*webproperty user links update*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementWebpropertyUserLinkUpdateCall.html) +* metadata + * [*columns list*](http://byron.github.io/google-apis-rs/google-analytics3/struct.MetadataColumnListCall.html) +* provisioning + * [*create account ticket*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ProvisioningCreateAccountTicketCall.html) + + +Upload supported by ... + +* [*uploads upload data management*](http://byron.github.io/google-apis-rs/google-analytics3/struct.ManagementUploadUploadDataCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-analytics3/struct.Analytics.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-analytics3/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-analytics3/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-analytics3/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.management().webproperty_user_links_insert(...).doit() +let r = hub.management().profile_user_links_insert(...).doit() +let r = hub.management().profile_user_links_update(...).doit() +let r = hub.management().account_user_links_update(...).doit() +let r = hub.management().webproperty_user_links_update(...).doit() +let r = hub.management().account_user_links_insert(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-analytics3 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-analytics3" as analytics3; +use analytics3::EntityUserLink; +use analytics3::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use analytics3::Analytics; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Analytics::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: EntityUserLink = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.management().profile_user_links_update(&req, "accountId", "webPropertyId", "profileId", "linkId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-analytics3/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-analytics3/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-analytics3/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-analytics3/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-analytics3/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-analytics3/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-analytics3/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-analytics3/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-analytics3/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-analytics3/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-analytics3/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-analytics3/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-analytics3/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **analytics3** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/analytics3/src/cmn.rs b/gen/analytics3/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/analytics3/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/analytics3/src/lib.rs b/gen/analytics3/src/lib.rs new file mode 100644 index 0000000000..d03092dc7f --- /dev/null +++ b/gen/analytics3/src/lib.rs @@ -0,0 +1,25711 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *analytics* crate version *0.1.0+20150308*, where *20150308* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *analytics* *v3* API can be found at the +//! [official documentation site](https://developers.google.com/analytics/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/analytics3). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Analytics.html) ... +//! +//! * data +//! * [*ga get*](struct.DataGaGetCall.html), [*mcf get*](struct.DataMcfGetCall.html) and [*realtime get*](struct.DataRealtimeGetCall.html) +//! * management +//! * [*account summaries list*](struct.ManagementAccountSummaryListCall.html), [*account user links delete*](struct.ManagementAccountUserLinkDeleteCall.html), [*account user links insert*](struct.ManagementAccountUserLinkInsertCall.html), [*account user links list*](struct.ManagementAccountUserLinkListCall.html), [*account user links update*](struct.ManagementAccountUserLinkUpdateCall.html), [*accounts list*](struct.ManagementAccountListCall.html), [*custom data sources list*](struct.ManagementCustomDataSourceListCall.html), [*custom dimensions get*](struct.ManagementCustomDimensionGetCall.html), [*custom dimensions insert*](struct.ManagementCustomDimensionInsertCall.html), [*custom dimensions list*](struct.ManagementCustomDimensionListCall.html), [*custom dimensions patch*](struct.ManagementCustomDimensionPatchCall.html), [*custom dimensions update*](struct.ManagementCustomDimensionUpdateCall.html), [*custom metrics get*](struct.ManagementCustomMetricGetCall.html), [*custom metrics insert*](struct.ManagementCustomMetricInsertCall.html), [*custom metrics list*](struct.ManagementCustomMetricListCall.html), [*custom metrics patch*](struct.ManagementCustomMetricPatchCall.html), [*custom metrics update*](struct.ManagementCustomMetricUpdateCall.html), [*experiments delete*](struct.ManagementExperimentDeleteCall.html), [*experiments get*](struct.ManagementExperimentGetCall.html), [*experiments insert*](struct.ManagementExperimentInsertCall.html), [*experiments list*](struct.ManagementExperimentListCall.html), [*experiments patch*](struct.ManagementExperimentPatchCall.html), [*experiments update*](struct.ManagementExperimentUpdateCall.html), [*filters delete*](struct.ManagementFilterDeleteCall.html), [*filters get*](struct.ManagementFilterGetCall.html), [*filters insert*](struct.ManagementFilterInsertCall.html), [*filters list*](struct.ManagementFilterListCall.html), [*filters patch*](struct.ManagementFilterPatchCall.html), [*filters update*](struct.ManagementFilterUpdateCall.html), [*goals get*](struct.ManagementGoalGetCall.html), [*goals insert*](struct.ManagementGoalInsertCall.html), [*goals list*](struct.ManagementGoalListCall.html), [*goals patch*](struct.ManagementGoalPatchCall.html), [*goals update*](struct.ManagementGoalUpdateCall.html), [*profile filter links delete*](struct.ManagementProfileFilterLinkDeleteCall.html), [*profile filter links get*](struct.ManagementProfileFilterLinkGetCall.html), [*profile filter links insert*](struct.ManagementProfileFilterLinkInsertCall.html), [*profile filter links list*](struct.ManagementProfileFilterLinkListCall.html), [*profile filter links patch*](struct.ManagementProfileFilterLinkPatchCall.html), [*profile filter links update*](struct.ManagementProfileFilterLinkUpdateCall.html), [*profile user links delete*](struct.ManagementProfileUserLinkDeleteCall.html), [*profile user links insert*](struct.ManagementProfileUserLinkInsertCall.html), [*profile user links list*](struct.ManagementProfileUserLinkListCall.html), [*profile user links update*](struct.ManagementProfileUserLinkUpdateCall.html), [*profiles delete*](struct.ManagementProfileDeleteCall.html), [*profiles get*](struct.ManagementProfileGetCall.html), [*profiles insert*](struct.ManagementProfileInsertCall.html), [*profiles list*](struct.ManagementProfileListCall.html), [*profiles patch*](struct.ManagementProfilePatchCall.html), [*profiles update*](struct.ManagementProfileUpdateCall.html), [*segments list*](struct.ManagementSegmentListCall.html), [*unsampled reports get*](struct.ManagementUnsampledReportGetCall.html), [*unsampled reports insert*](struct.ManagementUnsampledReportInsertCall.html), [*unsampled reports list*](struct.ManagementUnsampledReportListCall.html), [*uploads delete upload data*](struct.ManagementUploadDeleteUploadDataCall.html), [*uploads get*](struct.ManagementUploadGetCall.html), [*uploads list*](struct.ManagementUploadListCall.html), [*uploads upload data*](struct.ManagementUploadUploadDataCall.html), [*web property ad words links delete*](struct.ManagementWebPropertyAdWordsLinkDeleteCall.html), [*web property ad words links get*](struct.ManagementWebPropertyAdWordsLinkGetCall.html), [*web property ad words links insert*](struct.ManagementWebPropertyAdWordsLinkInsertCall.html), [*web property ad words links list*](struct.ManagementWebPropertyAdWordsLinkListCall.html), [*web property ad words links patch*](struct.ManagementWebPropertyAdWordsLinkPatchCall.html), [*web property ad words links update*](struct.ManagementWebPropertyAdWordsLinkUpdateCall.html), [*webproperties get*](struct.ManagementWebpropertyGetCall.html), [*webproperties insert*](struct.ManagementWebpropertyInsertCall.html), [*webproperties list*](struct.ManagementWebpropertyListCall.html), [*webproperties patch*](struct.ManagementWebpropertyPatchCall.html), [*webproperties update*](struct.ManagementWebpropertyUpdateCall.html), [*webproperty user links delete*](struct.ManagementWebpropertyUserLinkDeleteCall.html), [*webproperty user links insert*](struct.ManagementWebpropertyUserLinkInsertCall.html), [*webproperty user links list*](struct.ManagementWebpropertyUserLinkListCall.html) and [*webproperty user links update*](struct.ManagementWebpropertyUserLinkUpdateCall.html) +//! * metadata +//! * [*columns list*](struct.MetadataColumnListCall.html) +//! * provisioning +//! * [*create account ticket*](struct.ProvisioningCreateAccountTicketCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*uploads upload data management*](struct.ManagementUploadUploadDataCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Analytics.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.management().webproperty_user_links_insert(...).doit() +//! let r = hub.management().profile_user_links_insert(...).doit() +//! let r = hub.management().profile_user_links_update(...).doit() +//! let r = hub.management().account_user_links_update(...).doit() +//! let r = hub.management().webproperty_user_links_update(...).doit() +//! let r = hub.management().account_user_links_insert(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-analytics3 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-analytics3" as analytics3; +//! use analytics3::EntityUserLink; +//! use analytics3::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use analytics3::Analytics; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Analytics::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: EntityUserLink = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.management().profile_user_links_update(&req, "accountId", "webPropertyId", "profileId", "linkId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage Google Analytics Account users by email address + ManageUser, + + /// Create a new Google Analytics account along with its default property and view + Provision, + + /// View your Google Analytics data + Readonly, + + /// View Google Analytics user permissions + ManageUserReadonly, + + /// View and manage your Google Analytics data + Full, + + /// Edit Google Analytics management entities + Edit, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::ManageUser => "https://www.googleapis.com/auth/analytics.manage.users", + Scope::Provision => "https://www.googleapis.com/auth/analytics.provision", + Scope::Readonly => "https://www.googleapis.com/auth/analytics.readonly", + Scope::ManageUserReadonly => "https://www.googleapis.com/auth/analytics.manage.users.readonly", + Scope::Full => "https://www.googleapis.com/auth/analytics", + Scope::Edit => "https://www.googleapis.com/auth/analytics.edit", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Analytics related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// use analytics3::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use analytics3::Analytics; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_user_links_update(&req, "accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Analytics { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Analytics {} + +impl<'a, C, NC, A> Analytics + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Analytics { + Analytics { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn data(&'a self) -> DataMethods<'a, C, NC, A> { + DataMethods { hub: &self } + } + pub fn management(&'a self) -> ManagementMethods<'a, C, NC, A> { + ManagementMethods { hub: &self } + } + pub fn metadata(&'a self) -> MetadataMethods<'a, C, NC, A> { + MetadataMethods { hub: &self } + } + pub fn provisioning(&'a self) -> ProvisioningMethods<'a, C, NC, A> { + ProvisioningMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// JSON template for Analytics Custom Metric. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custom metrics patch management](struct.ManagementCustomMetricPatchCall.html) (request|response) +/// * [custom metrics insert management](struct.ManagementCustomMetricInsertCall.html) (request|response) +/// * [custom metrics get management](struct.ManagementCustomMetricGetCall.html) (response) +/// * [custom metrics update management](struct.ManagementCustomMetricUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomMetric { + /// Index of the custom metric. + pub index: Option, + /// Kind value for a custom metric. Set to "analytics#customMetric". It is a read-only field. + pub kind: Option, + /// Name of the custom metric. + pub name: Option, + /// Time the custom metric was created. + pub created: Option, + /// Max value of custom metric. + pub max_value: Option, + /// Min value of custom metric. + pub min_value: Option, + /// Time the custom metric was last modified. + pub updated: Option, + /// Property ID. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// Boolean indicating whether the custom metric is active. + pub active: Option, + /// Scope of the custom metric: HIT or PRODUCT. + pub scope: Option, + /// Parent link for the custom metric. Points to the property to which the custom metric belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Data type of custom metric. + #[serde(alias="type")] + pub type_: Option, + /// Custom metric ID. + pub id: Option, + /// Link for the custom metric + #[serde(alias="selfLink")] + pub self_link: Option, + /// Account ID. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for CustomMetric {} +impl ResponseResult for CustomMetric {} + + +/// JSON template for Analytics goal resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [goals get management](struct.ManagementGoalGetCall.html) (response) +/// * [goals update management](struct.ManagementGoalUpdateCall.html) (request|response) +/// * [goals patch management](struct.ManagementGoalPatchCall.html) (request|response) +/// * [goals insert management](struct.ManagementGoalInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Goal { + /// Time this goal was last modified. + pub updated: Option, + /// Internal ID for the web property to which this goal belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: Option, + /// Web property ID to which this goal belongs. The web property ID is of the form UA-XXXXX-YY. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// Determines whether this goal is active. + pub active: Option, + /// Goal ID. + pub id: Option, + /// Account ID to which this goal belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// Resource type for an Analytics goal. + pub kind: Option, + /// Details for the goal of the type VISIT_TIME_ON_SITE. + #[serde(alias="visitTimeOnSiteDetails")] + pub visit_time_on_site_details: Option, + /// Goal name. + pub name: Option, + /// Time this goal was created. + pub created: Option, + /// Goal type. Possible values are URL_DESTINATION, VISIT_TIME_ON_SITE, VISIT_NUM_PAGES, AND EVENT. + #[serde(alias="type")] + pub type_: Option, + /// Details for the goal of the type VISIT_NUM_PAGES. + #[serde(alias="visitNumPagesDetails")] + pub visit_num_pages_details: Option, + /// Goal value. + pub value: Option, + /// Details for the goal of the type EVENT. + #[serde(alias="eventDetails")] + pub event_details: Option, + /// View (Profile) ID to which this goal belongs. + #[serde(alias="profileId")] + pub profile_id: Option, + /// Parent link for a goal. Points to the view (profile) to which this goal belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Details for the goal of the type URL_DESTINATION. + #[serde(alias="urlDestinationDetails")] + pub url_destination_details: Option, + /// Link for this goal. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Goal {} +impl ResponseResult for Goal {} + + +/// Permissions the user has for this web property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WebpropertyPermissions { + /// All the permissions that the user has for this web property. These include any implied permissions (e.g., EDIT implies VIEW) or inherited permissions from the parent account. + pub effective: Vec, +} + +impl NestedType for WebpropertyPermissions {} +impl Part for WebpropertyPermissions {} + + +/// JSON template for a profile filter link. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterRef { + /// Kind value for filter reference. + pub kind: String, + /// Link for this filter. + pub href: String, + /// Account ID to which this filter belongs. + #[serde(alias="accountId")] + pub account_id: String, + /// Filter ID. + pub id: String, + /// Name of this filter. + pub name: String, +} + +impl Part for FilterRef {} + + +/// Details for the goal of the type EVENT. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalEventDetails { + /// List of event conditions. + #[serde(alias="eventConditions")] + pub event_conditions: Vec, + /// Determines if the event value should be used as the value for this goal. + #[serde(alias="useEventValue")] + pub use_event_value: bool, +} + +impl NestedType for GoalEventDetails {} +impl Part for GoalEventDetails {} + + +/// Request template for the delete upload data request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [uploads delete upload data management](struct.ManagementUploadDeleteUploadDataCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AnalyticsDataimportDeleteUploadDataRequest { + /// A list of upload UIDs. + #[serde(alias="customDataImportUids")] + pub custom_data_import_uids: Option>, +} + +impl RequestValue for AnalyticsDataimportDeleteUploadDataRequest {} + + +/// Information for the view (profile), for which the real time data was requested. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RealtimeDataProfileInfo { + /// Internal ID for the web property to which this view (profile) belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// Table ID for view (profile). + #[serde(alias="tableId")] + pub table_id: String, + /// Web Property ID to which this view (profile) belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: String, + /// View (Profile) ID. + #[serde(alias="profileId")] + pub profile_id: String, + /// View (Profile) name. + #[serde(alias="profileName")] + pub profile_name: String, + /// Account ID to which this view (profile) belongs. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl NestedType for RealtimeDataProfileInfo {} +impl Part for RealtimeDataProfileInfo {} + + +/// Real time data request query parameters. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RealtimeDataQuery { + /// Maximum results per page. + #[serde(alias="max-results")] + pub max_results: i32, + /// List of dimensions or metrics based on which real time data is sorted. + pub sort: Vec, + /// List of real time metrics. + pub metrics: Vec, + /// List of real time dimensions. + pub dimensions: String, + /// Comma-separated list of dimension or metric filters. + pub filters: String, + /// Unique table ID. + pub ids: String, +} + +impl NestedType for RealtimeDataQuery {} +impl Part for RealtimeDataQuery {} + + +/// JSON template for a linked view (profile). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProfileRef { + /// Analytics view (profile) reference. + pub kind: String, + /// Link for this view (profile). + pub href: String, + /// Name of this view (profile). + pub name: String, + /// Web property ID of the form UA-XXXXX-YY to which this view (profile) belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: String, + /// Account ID to which this view (profile) belongs. + #[serde(alias="accountId")] + pub account_id: String, + /// Internal ID for the web property to which this view (profile) belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// View (Profile) ID. + pub id: String, +} + +impl Part for ProfileRef {} + + +/// Multi-Channel Funnels data for a given view (profile). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [mcf get data](struct.DataMcfGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfData { + /// Resource type. + pub kind: String, + /// Analytics data rows, where each row contains a list of dimension values followed by the metric values. The order of dimensions and metrics is same as specified in the request. + pub rows: Vec>, + /// Determines if the Analytics data contains sampled data. + #[serde(alias="containsSampledData")] + pub contains_sampled_data: bool, + /// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. + #[serde(alias="columnHeaders")] + pub column_headers: Vec, + /// The total number of rows for the query, regardless of the number of rows in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// The maximum number of rows the response can contain, regardless of the actual number of rows returned. Its value ranges from 1 to 10,000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Total values for the requested metrics over all the results, not just the results returned in this response. The order of the metric totals is same as the metric order specified in the request. + #[serde(alias="totalsForAllResults")] + pub totals_for_all_results: HashMap, + /// Link to next page for this Analytics data query. + #[serde(alias="nextLink")] + pub next_link: String, + /// The number of samples used to calculate the result. + #[serde(alias="sampleSize")] + pub sample_size: String, + /// Analytics data request query parameters. + pub query: McfDataQuery, + /// Link to previous page for this Analytics data query. + #[serde(alias="previousLink")] + pub previous_link: String, + /// Information for the view (profile), for which the Analytics data was requested. + #[serde(alias="profileInfo")] + pub profile_info: McfDataProfileInfo, + /// Unique ID for this data response. + pub id: String, + /// Link to this page. + #[serde(alias="selfLink")] + pub self_link: String, + /// Total size of the sample space from which the samples were selected. + #[serde(alias="sampleSpace")] + pub sample_space: String, +} + +impl ResponseResult for McfData {} + + +/// Lists Analytics custom data sources to which the user has access. Each resource in the collection corresponds to a single Analytics custom data source. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custom data sources list management](struct.ManagementCustomDataSourceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomDataSources { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// Collection of custom data sources. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this custom data source collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this custom data source collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for CustomDataSources {} + + +/// A goal collection lists Analytics goals to which the user has access. Each view (profile) can have a set of goals. Each resource in the Goal collection corresponds to a single Analytics goal. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [goals list management](struct.ManagementGoalListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Goals { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of goals. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this goal collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this goal collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of resources in the result. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Goals {} + + +/// JSON template for Analytics account entry. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Account { + /// Resource type for Analytics account. + pub kind: String, + /// Account name. + pub name: String, + /// Time the account was created. + pub created: String, + /// Time the account was last modified. + pub updated: String, + /// Child link for an account entry. Points to the list of web properties for this account. + #[serde(alias="childLink")] + pub child_link: AccountChildLink, + /// Account ID. + pub id: String, + /// Link for this account. + #[serde(alias="selfLink")] + pub self_link: String, + /// Permissions the user has for this account. + pub permissions: AccountPermissions, +} + +impl Part for Account {} + + +/// Analytics data for a given view (profile). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [ga get data](struct.DataGaGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaData { + /// Determines if Analytics data contains samples. + #[serde(alias="containsSampledData")] + pub contains_sampled_data: bool, + /// Link to previous page for this Analytics data query. + #[serde(alias="previousLink")] + pub previous_link: String, + /// no description provided + #[serde(alias="dataTable")] + pub data_table: GaDataDataTable, + /// Analytics data request query parameters. + pub query: GaDataQuery, + /// Total values for the requested metrics over all the results, not just the results returned in this response. The order of the metric totals is same as the metric order specified in the request. + #[serde(alias="totalsForAllResults")] + pub totals_for_all_results: HashMap, + /// Unique ID for this data response. + pub id: String, + /// Resource type. + pub kind: String, + /// Analytics data rows, where each row contains a list of dimension values followed by the metric values. The order of dimensions and metrics is same as specified in the request. + pub rows: Vec>, + /// The total number of rows for the query, regardless of the number of rows in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// The maximum number of rows the response can contain, regardless of the actual number of rows returned. Its value ranges from 1 to 10,000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to next page for this Analytics data query. + #[serde(alias="nextLink")] + pub next_link: String, + /// The number of samples used to calculate the result. + #[serde(alias="sampleSize")] + pub sample_size: String, + /// Information for the view (profile), for which the Analytics data was requested. + #[serde(alias="profileInfo")] + pub profile_info: GaDataProfileInfo, + /// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. + #[serde(alias="columnHeaders")] + pub column_headers: Vec, + /// Link to this page. + #[serde(alias="selfLink")] + pub self_link: String, + /// Total size of the sample space from which the samples were selected. + #[serde(alias="sampleSpace")] + pub sample_space: String, +} + +impl ResponseResult for GaData {} + + +/// Parent link for an experiment. Points to the view (profile) to which this experiment belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExperimentParentLink { + /// Link to the view (profile) to which this experiment belongs. This field is read-only. + pub href: String, + /// Value is "analytics#profile". This field is read-only. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for ExperimentParentLink {} +impl Part for ExperimentParentLink {} + + +/// JSON template for Analytics unsampled report resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [unsampled reports insert management](struct.ManagementUnsampledReportInsertCall.html) (request|response) +/// * [unsampled reports get management](struct.ManagementUnsampledReportGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UnsampledReport { + /// Status of this unsampled report. Possible values are PENDING, COMPLETED, or FAILED. + pub status: Option, + /// Time this unsampled report was last modified. + pub updated: Option, + /// The type of download you need to use for the report data file. + #[serde(alias="downloadType")] + pub download_type: Option, + /// The start date for the unsampled report. + #[serde(alias="start-date")] + pub start_date: Option, + /// Download details for a file stored in Google Drive. + #[serde(alias="driveDownloadDetails")] + pub drive_download_details: Option, + /// The metrics for the unsampled report. + pub metrics: Option, + /// The filters for the unsampled report. + pub filters: Option, + /// Web property ID to which this unsampled report belongs. The web property ID is of the form UA-XXXXX-YY. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// The segment for the unsampled report. + pub segment: Option, + /// Unsampled report ID. + pub id: Option, + /// Account ID to which this unsampled report belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// Resource type for an Analytics unsampled report. + pub kind: Option, + /// Download details for a file stored in Google Cloud Storage. + #[serde(alias="cloudStorageDownloadDetails")] + pub cloud_storage_download_details: Option, + /// The dimensions for the unsampled report. + pub dimensions: Option, + /// Time this unsampled report was created. + pub created: Option, + /// Title of the unsampled report. + pub title: Option, + /// View (Profile) ID to which this unsampled report belongs. + #[serde(alias="profileId")] + pub profile_id: Option, + /// The end date for the unsampled report. + #[serde(alias="end-date")] + pub end_date: Option, + /// Link for this unsampled report. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for UnsampledReport {} +impl ResponseResult for UnsampledReport {} + + +/// Parent link for this web property. Points to the account to which this web property belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WebpropertyParentLink { + /// Link to the account for this web property. + pub href: String, + /// Type of the parent link. Its value is "analytics#account". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for WebpropertyParentLink {} +impl Part for WebpropertyParentLink {} + + +/// Parent link for this view (profile). Points to the web property to which this view (profile) belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProfileParentLink { + /// Link to the web property to which this view (profile) belongs. + pub href: String, + /// Value is "analytics#webproperty". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for ProfileParentLink {} +impl Part for ProfileParentLink {} + + +/// JSON template for a user reference. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserRef { + /// no description provided + pub kind: String, + /// Email ID of this user. + pub email: String, + /// User ID. + pub id: String, +} + +impl Part for UserRef {} + + +/// An account collection provides a list of Analytics accounts to which a user has access. The account collection is the entry point to all management information. Each resource in the collection corresponds to a single Analytics account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [accounts list management](struct.ManagementAccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Accounts { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of accounts. + pub items: Vec, + /// The maximum number of entries the response can contain, regardless of the actual number of entries returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Previous link for this account collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the entries, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Next link for this account collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Accounts {} + + +/// Details for the filter of the type ADVANCED. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterAdvancedDetails { + /// Field A. + #[serde(alias="fieldA")] + pub field_a: String, + /// Indicates if the existing value of the output field, if any, should be overridden by the output expression. + #[serde(alias="overrideOutputField")] + pub override_output_field: bool, + /// Indicates if field A is required to match. + #[serde(alias="fieldARequired")] + pub field_a_required: bool, + /// Expression used to construct the output value. + #[serde(alias="outputConstructor")] + pub output_constructor: String, + /// Indicates if field B is required to match. + #[serde(alias="fieldBRequired")] + pub field_b_required: bool, + /// Indicates if the filter expressions are case sensitive. + #[serde(alias="caseSensitive")] + pub case_sensitive: bool, + /// Field B. + #[serde(alias="fieldB")] + pub field_b: String, + /// Expression to extract from field B. + #[serde(alias="extractB")] + pub extract_b: String, + /// Expression to extract from field A. + #[serde(alias="extractA")] + pub extract_a: String, + /// Output field. + #[serde(alias="outputToField")] + pub output_to_field: String, +} + +impl NestedType for FilterAdvancedDetails {} +impl Part for FilterAdvancedDetails {} + + +/// JSON template for an Analytics WebPropertySummary. WebPropertySummary returns basic information (i.e., summary) for a web property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct WebPropertySummary { + /// Website url for this web property. + #[serde(alias="websiteUrl")] + pub website_url: String, + /// Resource type for Analytics WebPropertySummary. + pub kind: String, + /// Web property name. + pub name: String, + /// Level for this web property. Possible values are STANDARD or PREMIUM. + pub level: String, + /// Internal ID for this web property. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// List of profiles under this web property. + pub profiles: Vec, + /// Web property ID of the form UA-XXXXX-YY. + pub id: String, +} + +impl Part for WebPropertySummary {} + + +/// JSON template for an Analytics account ticket. The account ticket consists of the ticket ID and the basic information for the account, property and profile. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [create account ticket provisioning](struct.ProvisioningCreateAccountTicketCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountTicket { + /// View (Profile) for the account. + pub profile: Option, + /// Account for this ticket. + pub account: Option, + /// Account ticket ID used to access the account ticket. + pub id: Option, + /// Web property for the account. + pub webproperty: Option, + /// Resource type for account ticket. + pub kind: Option, + /// Redirect URI where the user will be sent after accepting Terms of Service. Must be configured in APIs console as a callback URL. + #[serde(alias="redirectUri")] + pub redirect_uri: Option, +} + +impl RequestValue for AccountTicket {} +impl ResponseResult for AccountTicket {} + + +/// Information for the view (profile), for which the Analytics data was requested. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfDataProfileInfo { + /// Internal ID for the web property to which this view (profile) belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// Table ID for view (profile). + #[serde(alias="tableId")] + pub table_id: String, + /// Web Property ID to which this view (profile) belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: String, + /// View (Profile) ID. + #[serde(alias="profileId")] + pub profile_id: String, + /// View (Profile) name. + #[serde(alias="profileName")] + pub profile_name: String, + /// Account ID to which this view (profile) belongs. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl NestedType for McfDataProfileInfo {} +impl Part for McfDataProfileInfo {} + + +/// Download details for a file stored in Google Cloud Storage. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UnsampledReportCloudStorageDownloadDetails { + /// Id of the bucket the file object is stored in. + #[serde(alias="bucketId")] + pub bucket_id: String, + /// Id of the file object containing the report data. + #[serde(alias="objectId")] + pub object_id: String, +} + +impl NestedType for UnsampledReportCloudStorageDownloadDetails {} +impl Part for UnsampledReportCloudStorageDownloadDetails {} + + +/// Details for the goal of the type VISIT_TIME_ON_SITE. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalVisitTimeOnSiteDetails { + /// Type of comparison. Possible values are LESS_THAN or GREATER_THAN. + #[serde(alias="comparisonType")] + pub comparison_type: String, + /// Value used for this comparison. + #[serde(alias="comparisonValue")] + pub comparison_value: String, +} + +impl NestedType for GoalVisitTimeOnSiteDetails {} +impl Part for GoalVisitTimeOnSiteDetails {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataDataTable { + /// no description provided + pub rows: Vec, + /// no description provided + pub cols: Vec, +} + +impl NestedType for GaDataDataTable {} +impl Part for GaDataDataTable {} + + +/// JSON template for an Analytics Entity-User Link. Returns permissions that a user has for an entity. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [webproperty user links insert management](struct.ManagementWebpropertyUserLinkInsertCall.html) (request|response) +/// * [profile user links insert management](struct.ManagementProfileUserLinkInsertCall.html) (request|response) +/// * [profile user links update management](struct.ManagementProfileUserLinkUpdateCall.html) (request|response) +/// * [account user links update management](struct.ManagementAccountUserLinkUpdateCall.html) (request|response) +/// * [webproperty user links update management](struct.ManagementWebpropertyUserLinkUpdateCall.html) (request|response) +/// * [account user links insert management](struct.ManagementAccountUserLinkInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EntityUserLink { + /// Resource type for entity user link. + pub kind: Option, + /// User reference. + #[serde(alias="userRef")] + pub user_ref: Option, + /// Permissions the user has for this entity. + pub permissions: Option, + /// Entity user link ID + pub id: Option, + /// Self link for this resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Entity for this link. It can be an account, a web property, or a view (profile). + pub entity: Option, +} + +impl RequestValue for EntityUserLink {} +impl ResponseResult for EntityUserLink {} + + +/// An AccountSummary collection lists a summary of accounts, properties and views (profiles) to which the user has access. Each resource in the collection corresponds to a single AccountSummary. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [account summaries list management](struct.ManagementAccountSummaryListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountSummaries { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of AccountSummaries. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this AccountSummary collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this AccountSummary collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for AccountSummaries {} + + +/// A custom dimension collection lists Analytics custom dimensions to which the user has access. Each resource in the collection corresponds to a single Analytics custom dimension. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custom dimensions list management](struct.ManagementCustomDimensionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomDimensions { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// Collection of custom dimensions. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this custom dimension collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this custom dimension collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for CustomDimensions {} + + +/// Download details for a file stored in Google Drive. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UnsampledReportDriveDownloadDetails { + /// Id of the document/file containing the report data. + #[serde(alias="documentId")] + pub document_id: String, +} + +impl NestedType for UnsampledReportDriveDownloadDetails {} +impl Part for UnsampledReportDriveDownloadDetails {} + + +/// Details for the goal of the type URL_DESTINATION. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalUrlDestinationDetails { + /// URL for this goal. + pub url: String, + /// Determines if the goal URL must exactly match the capitalization of visited URLs. + #[serde(alias="caseSensitive")] + pub case_sensitive: bool, + /// Match type for the goal URL. Possible values are HEAD, EXACT, or REGEX. + #[serde(alias="matchType")] + pub match_type: String, + /// List of steps configured for this goal funnel. + pub steps: Vec, + /// Determines if the first step in this goal is required. + #[serde(alias="firstStepRequired")] + pub first_step_required: bool, +} + +impl NestedType for GoalUrlDestinationDetails {} +impl Part for GoalUrlDestinationDetails {} + + +/// Metadata returned for an upload operation. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [uploads get management](struct.ManagementUploadGetCall.html) (response) +/// * [uploads upload data management](struct.ManagementUploadUploadDataCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Upload { + /// Upload status. Possible values: PENDING, COMPLETED, FAILED, DELETING, DELETED. + pub status: String, + /// Resource type for Analytics upload. + pub kind: String, + /// Data import errors collection. + pub errors: Vec, + /// Custom data source Id to which this data import belongs. + #[serde(alias="customDataSourceId")] + pub custom_data_source_id: String, + /// A unique ID for this upload. + pub id: String, + /// Account Id to which this upload belongs. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl ResponseResult for Upload {} + + +/// A view (profile) collection lists Analytics views (profiles) to which the user has access. Each resource in the collection corresponds to a single Analytics view (profile). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [profiles list management](struct.ManagementProfileListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Profiles { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of views (profiles). + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this view (profile) collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this view (profile) collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Profiles {} + + +/// Permissions the user has for this account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountPermissions { + /// All the permissions that the user has for this account. These include any implied permissions (e.g., EDIT implies VIEW). + pub effective: Vec, +} + +impl NestedType for AccountPermissions {} +impl Part for AccountPermissions {} + + +/// Information for the view (profile), for which the Analytics data was requested. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataProfileInfo { + /// Internal ID for the web property to which this view (profile) belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// Table ID for view (profile). + #[serde(alias="tableId")] + pub table_id: String, + /// Web Property ID to which this view (profile) belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: String, + /// View (Profile) ID. + #[serde(alias="profileId")] + pub profile_id: String, + /// View (Profile) name. + #[serde(alias="profileName")] + pub profile_name: String, + /// Account ID to which this view (profile) belongs. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl NestedType for GaDataProfileInfo {} +impl Part for GaDataProfileInfo {} + + +/// Parent link for this filter. Points to the account to which this filter belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterParentLink { + /// Link to the account to which this filter belongs. + pub href: String, + /// Value is "analytics#account". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for FilterParentLink {} +impl Part for FilterParentLink {} + + +/// A web property collection lists Analytics web properties to which the user has access. Each resource in the collection corresponds to a single Analytics web property. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [webproperties list management](struct.ManagementWebpropertyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Webproperties { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of web properties. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this web property collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this web property collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Webproperties {} + + +/// Permissions the user has for this entity. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EntityUserLinkPermissions { + /// Permissions that a user has been assigned at this very level. Does not include any implied or inherited permissions. Local permissions are modifiable. + pub local: Vec, + /// Effective permissions represent all the permissions that a user has for this entity. These include any implied permissions (e.g., EDIT implies VIEW) or inherited permissions from the parent entity. Effective permissions are read-only. + pub effective: Vec, +} + +impl NestedType for EntityUserLinkPermissions {} +impl Part for EntityUserLinkPermissions {} + + +/// JSON template for an Analytics profile filter link. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [profile filter links update management](struct.ManagementProfileFilterLinkUpdateCall.html) (request|response) +/// * [profile filter links get management](struct.ManagementProfileFilterLinkGetCall.html) (response) +/// * [profile filter links insert management](struct.ManagementProfileFilterLinkInsertCall.html) (request|response) +/// * [profile filter links patch management](struct.ManagementProfileFilterLinkPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProfileFilterLink { + /// Filter for this link. + #[serde(alias="filterRef")] + pub filter_ref: Option, + /// Resource type for Analytics filter. + pub kind: Option, + /// Link for this profile filter link. + #[serde(alias="selfLink")] + pub self_link: Option, + /// View (Profile) for this link. + #[serde(alias="profileRef")] + pub profile_ref: Option, + /// Profile filter link ID. + pub id: Option, + /// The rank of this profile filter link relative to the other filters linked to the same profile. + /// For readonly (i.e., list and get) operations, the rank always starts at 1. + /// For write (i.e., create, update, or delete) operations, you may specify a value between 0 and 255 inclusively, [0, 255]. In order to insert a link at the end of the list, either don't specify a rank or set a rank to a number greater than the largest rank in the list. In order to insert a link to the beginning of the list specify a rank that is less than or equal to 1. The new link will move all existing filters with the same or lower rank down the list. After the link is inserted/updated/deleted all profile filter links will be renumbered starting at 1. + pub rank: Option, +} + +impl RequestValue for ProfileFilterLink {} +impl ResponseResult for ProfileFilterLink {} + + +/// JSON template for an Analytics AccountSummary. An AccountSummary is a lightweight tree comprised of properties/profiles. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountSummary { + /// Resource type for Analytics AccountSummary. + pub kind: String, + /// List of web properties under this account. + #[serde(alias="webProperties")] + pub web_properties: Vec, + /// Account ID. + pub id: String, + /// Account name. + pub name: String, +} + +impl Part for AccountSummary {} + + +/// JSON template for an Analytics web property. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [webproperties insert management](struct.ManagementWebpropertyInsertCall.html) (request|response) +/// * [webproperties update management](struct.ManagementWebpropertyUpdateCall.html) (request|response) +/// * [webproperties get management](struct.ManagementWebpropertyGetCall.html) (response) +/// * [webproperties patch management](struct.ManagementWebpropertyPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Webproperty { + /// Time this web property was last modified. + pub updated: Option, + /// Default view (profile) ID. + #[serde(alias="defaultProfileId")] + pub default_profile_id: Option, + /// View (Profile) count for this web property. + #[serde(alias="profileCount")] + pub profile_count: Option, + /// Internal ID for this web property. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: Option, + /// Child link for this web property. Points to the list of views (profiles) for this web property. + #[serde(alias="childLink")] + pub child_link: Option, + /// The industry vertical/category selected for this web property. + #[serde(alias="industryVertical")] + pub industry_vertical: Option, + /// Web property ID of the form UA-XXXXX-YY. + pub id: Option, + /// Account ID to which this web property belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// Resource type for Analytics WebProperty. + pub kind: Option, + /// Name of this web property. + pub name: Option, + /// Time this web property was created. + pub created: Option, + /// Level for this web property. Possible values are STANDARD or PREMIUM. + pub level: Option, + /// Website url for this web property. + #[serde(alias="websiteUrl")] + pub website_url: Option, + /// Parent link for this web property. Points to the account to which this web property belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Permissions the user has for this web property. + pub permissions: Option, + /// Link for this web property. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Webproperty {} +impl ResponseResult for Webproperty {} + + +/// Real time data for a given view (profile). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [realtime get data](struct.DataRealtimeGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RealtimeData { + /// Resource type. + pub kind: String, + /// Real time data rows, where each row contains a list of dimension values followed by the metric values. The order of dimensions and metrics is same as specified in the request. + pub rows: Vec>, + /// The total number of rows for the query, regardless of the number of rows in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// Information for the view (profile), for which the real time data was requested. + #[serde(alias="profileInfo")] + pub profile_info: RealtimeDataProfileInfo, + /// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. + #[serde(alias="columnHeaders")] + pub column_headers: Vec, + /// Real time data request query parameters. + pub query: RealtimeDataQuery, + /// Total values for the requested metrics over all the results, not just the results returned in this response. The order of the metric totals is same as the metric order specified in the request. + #[serde(alias="totalsForAllResults")] + pub totals_for_all_results: HashMap, + /// Unique ID for this data response. + pub id: String, + /// Link to this page. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for RealtimeData {} + + +/// Details for the filter of the type SEARCH_AND_REPLACE. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterSearchAndReplaceDetails { + /// Determines if the filter is case sensitive. + #[serde(alias="caseSensitive")] + pub case_sensitive: bool, + /// Term to search. + #[serde(alias="searchString")] + pub search_string: String, + /// Term to replace the search term with. + #[serde(alias="replaceString")] + pub replace_string: String, + /// Field to use in the filter. + pub field: String, +} + +impl NestedType for FilterSearchAndReplaceDetails {} +impl Part for FilterSearchAndReplaceDetails {} + + +/// JSON template for Analytics experiment resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [experiments patch management](struct.ManagementExperimentPatchCall.html) (request|response) +/// * [experiments insert management](struct.ManagementExperimentInsertCall.html) (request|response) +/// * [experiments update management](struct.ManagementExperimentUpdateCall.html) (request|response) +/// * [experiments get management](struct.ManagementExperimentGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Experiment { + /// Experiment status. Possible values: "DRAFT", "READY_TO_RUN", "RUNNING", "ENDED". Experiments can be created in the "DRAFT", "READY_TO_RUN" or "RUNNING" state. This field is required when creating an experiment. + pub status: Option, + /// A floating-point number between 0 and 1. Specifies the fraction of the traffic that participates in the experiment. Can be changed for a running experiment. This field may not be changed for an experiments whose status is ENDED. + #[serde(alias="trafficCoverage")] + pub traffic_coverage: Option, + /// Notes about this experiment. + pub description: Option, + /// Web property ID to which this experiment belongs. The web property ID is of the form UA-XXXXX-YY. This field is read-only. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// Time the experiment was last modified. This field is read-only. + pub updated: Option, + /// Internal ID for the web property to which this experiment belongs. This field is read-only. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: Option, + /// A floating-point number between 0 and 1. Specifies the necessary confidence level to choose a winner. This field may not be changed for an experiments whose status is ENDED. + #[serde(alias="winnerConfidenceLevel")] + pub winner_confidence_level: Option, + /// The starting time of the experiment (the time the status changed from READY_TO_RUN to RUNNING). This field is present only if the experiment has started. This field is read-only. + #[serde(alias="startTime")] + pub start_time: Option, + /// Whether the objectiveMetric should be minimized or maximized. Possible values: "MAXIMUM", "MINIMUM". Optional--defaults to "MAXIMUM". Cannot be specified without objectiveMetric. Cannot be modified when status is "RUNNING" or "ENDED". + #[serde(alias="optimizationType")] + pub optimization_type: Option, + /// Boolean specifying whether a winner has been found for this experiment. This field is read-only. + #[serde(alias="winnerFound")] + pub winner_found: Option, + /// The metric that the experiment is optimizing. Valid values: "ga:goal(n)Completions", "ga:adsenseAdsClicks", "ga:adsenseAdsViewed", "ga:adsenseRevenue", "ga:bounces", "ga:pageviews", "ga:sessionDuration", "ga:transactions", "ga:transactionRevenue". This field is required if status is "RUNNING" and servingFramework is one of "REDIRECT" or "API". + #[serde(alias="objectiveMetric")] + pub objective_metric: Option, + /// Experiment ID. Required for patch and update. Disallowed for create. + pub id: Option, + /// Boolean specifying whether to distribute traffic evenly across all variations. If the value is False, content experiments follows the default behavior of adjusting traffic dynamically based on variation performance. Optional -- defaults to False. This field may not be changed for an experiment whose status is ENDED. + #[serde(alias="equalWeighting")] + pub equal_weighting: Option, + /// Account ID to which this experiment belongs. This field is read-only. + #[serde(alias="accountId")] + pub account_id: Option, + /// Resource type for an Analytics experiment. This field is read-only. + pub kind: Option, + /// Experiment name. This field may not be changed for an experiment whose status is ENDED. This field is required when creating an experiment. + pub name: Option, + /// Time the experiment was created. This field is read-only. + pub created: Option, + /// Why the experiment ended. Possible values: "STOPPED_BY_USER", "WINNER_FOUND", "EXPERIMENT_EXPIRED", "ENDED_WITH_NO_WINNER", "GOAL_OBJECTIVE_CHANGED". "ENDED_WITH_NO_WINNER" means that the experiment didn't expire but no winner was projected to be found. If the experiment status is changed via the API to ENDED this field is set to STOPPED_BY_USER. This field is read-only. + #[serde(alias="reasonExperimentEnded")] + pub reason_experiment_ended: Option, + /// Array of variations. The first variation in the array is the original. The number of variations may not change once an experiment is in the RUNNING state. At least two variations are required before status can be set to RUNNING. + pub variations: Option>, + /// The snippet of code to include on the control page(s). This field is read-only. + pub snippet: Option, + /// If true, the end user will be able to edit the experiment via the Google Analytics user interface. + #[serde(alias="editableInGaUi")] + pub editable_in_ga_ui: Option, + /// Boolean specifying whether variations URLS are rewritten to match those of the original. This field may not be changed for an experiments whose status is ENDED. + #[serde(alias="rewriteVariationUrlsAsOriginal")] + pub rewrite_variation_urls_as_original: Option, + /// An integer number in [3, 90]. Specifies the minimum length of the experiment. Can be changed for a running experiment. This field may not be changed for an experiments whose status is ENDED. + #[serde(alias="minimumExperimentLengthInDays")] + pub minimum_experiment_length_in_days: Option, + /// View (Profile) ID to which this experiment belongs. This field is read-only. + #[serde(alias="profileId")] + pub profile_id: Option, + /// Parent link for an experiment. Points to the view (profile) to which this experiment belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// The ending time of the experiment (the time the status changed from RUNNING to ENDED). This field is present only if the experiment has ended. This field is read-only. + #[serde(alias="endTime")] + pub end_time: Option, + /// The framework used to serve the experiment variations and evaluate the results. One of: + /// - REDIRECT: Google Analytics redirects traffic to different variation pages, reports the chosen variation and evaluates the results. + /// - API: Google Analytics chooses and reports the variation to serve and evaluates the results; the caller is responsible for serving the selected variation. + /// - EXTERNAL: The variations will be served externally and the chosen variation reported to Google Analytics. The caller is responsible for serving the selected variation and evaluating the results. + #[serde(alias="servingFramework")] + pub serving_framework: Option, + /// Link for this experiment. This field is read-only. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Experiment {} +impl ResponseResult for Experiment {} + + +/// A custom metric collection lists Analytics custom metrics to which the user has access. Each resource in the collection corresponds to a single Analytics custom metric. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custom metrics list management](struct.ManagementCustomMetricListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomMetrics { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// Collection of custom metrics. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this custom metric collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this custom metric collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for CustomMetrics {} + + +/// Analytics data request query parameters. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataQuery { + /// Maximum results per page. + #[serde(alias="max-results")] + pub max_results: i32, + /// List of dimensions or metrics based on which Analytics data is sorted. + pub sort: Vec, + /// List of analytics dimensions. + pub dimensions: String, + /// Start date. + #[serde(alias="start-date")] + pub start_date: String, + /// Start index. + #[serde(alias="start-index")] + pub start_index: i32, + /// End date. + #[serde(alias="end-date")] + pub end_date: String, + /// Unique table ID. + pub ids: String, + /// List of analytics metrics. + pub metrics: Vec, + /// Desired sampling level + #[serde(alias="samplingLevel")] + pub sampling_level: String, + /// Comma-separated list of dimension or metric filters. + pub filters: String, + /// Analytics advanced segment. + pub segment: String, +} + +impl NestedType for GaDataQuery {} +impl Part for GaDataQuery {} + + +/// Lists columns (dimensions and metrics) for a particular report type. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [columns list metadata](struct.MetadataColumnListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Columns { + /// List of columns for a report type. + pub items: Vec, + /// Collection type. + pub kind: String, + /// Etag of collection. This etag can be compared with the last response etag to check if response has changed. + pub etag: String, + /// Total number of columns returned in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// List of attributes names returned by columns. + #[serde(alias="attributeNames")] + pub attribute_names: Vec, +} + +impl ResponseResult for Columns {} + + +/// JSON template for an Analytics filter expression. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterExpression { + /// Determines if the filter is case sensitive. + #[serde(alias="caseSensitive")] + pub case_sensitive: bool, + /// Kind value for filter expression + pub kind: String, + /// Match type for this filter. Possible values are BEGINS_WITH, EQUAL, ENDS_WITH, CONTAINS, MATCHES. Include and Exclude filters can use any match type. Match type is not applicable to Upper case and Lower case filters. Search and Replace expressions in the Search and Replace filter and all filter expressions in the Advanced filter default to MATCHES. User should not set match type for those filters. + #[serde(alias="matchType")] + pub match_type: String, + /// Filter expression value + #[serde(alias="expressionValue")] + pub expression_value: String, + /// Field to filter. Possible values: + /// - Content and Traffic + /// - PAGE_REQUEST_URI, + /// - PAGE_HOSTNAME, + /// - PAGE_TITLE, + /// - REFERRAL, + /// - COST_DATA_URI (Campaign target URL), + /// - HIT_TYPE, + /// - INTERNAL_SEARCH_TERM, + /// - INTERNAL_SEARCH_TYPE, + /// - SOURCE_PROPERTY_TRACKING_ID, + /// - Campaign or AdGroup + /// - CAMPAIGN_SOURCE, + /// - CAMPAIGN_MEDIUM, + /// - CAMPAIGN_NAME, + /// - CAMPAIGN_AD_GROUP, + /// - CAMPAIGN_TERM, + /// - CAMPAIGN_CONTENT, + /// - CAMPAIGN_CODE, + /// - CAMPAIGN_REFERRAL_PATH, + /// - E-Commerce + /// - TRANSACTION_COUNTRY, + /// - TRANSACTION_REGION, + /// - TRANSACTION_CITY, + /// - TRANSACTION_AFFILIATION (Store or order location), + /// - ITEM_NAME, + /// - ITEM_CODE, + /// - ITEM_VARIATION, + /// - TRANSACTION_ID, + /// - TRANSACTION_CURRENCY_CODE, + /// - PRODUCT_ACTION_TYPE, + /// - Audience/Users + /// - BROWSER, + /// - BROWSER_VERSION, + /// - BROWSER_SIZE, + /// - PLATFORM, + /// - PLATFORM_VERSION, + /// - LANGUAGE, + /// - SCREEN_RESOLUTION, + /// - SCREEN_COLORS, + /// - JAVA_ENABLED (Boolean Field), + /// - FLASH_VERSION, + /// - GEO_SPEED (Connection speed), + /// - VISITOR_TYPE, + /// - GEO_ORGANIZATION (ISP organization), + /// - GEO_DOMAIN, + /// - GEO_IP_ADDRESS, + /// - GEO_IP_VERSION, + /// - Location + /// - GEO_COUNTRY, + /// - GEO_REGION, + /// - GEO_CITY, + /// - Event + /// - EVENT_CATEGORY, + /// - EVENT_ACTION, + /// - EVENT_LABEL, + /// - Other + /// - CUSTOM_FIELD_1, + /// - CUSTOM_FIELD_2, + /// - USER_DEFINED_VALUE, + /// - Application + /// - APP_ID, + /// - APP_INSTALLER_ID, + /// - APP_NAME, + /// - APP_VERSION, + /// - SCREEN, + /// - IS_APP (Boolean Field), + /// - IS_FATAL_EXCEPTION (Boolean Field), + /// - EXCEPTION_DESCRIPTION, + /// - Mobile device + /// - IS_MOBILE (Boolean Field, Deprecated. Use DEVICE_CATEGORY=mobile), + /// - IS_TABLET (Boolean Field, Deprecated. Use DEVICE_CATEGORY=tablet), + /// - DEVICE_CATEGORY, + /// - MOBILE_HAS_QWERTY_KEYBOARD (Boolean Field), + /// - MOBILE_HAS_NFC_SUPPORT (Boolean Field), + /// - MOBILE_HAS_CELLULAR_RADIO (Boolean Field), + /// - MOBILE_HAS_WIFI_SUPPORT (Boolean Field), + /// - MOBILE_BRAND_NAME, + /// - MOBILE_MODEL_NAME, + /// - MOBILE_MARKETING_NAME, + /// - MOBILE_POINTING_METHOD, + /// - Social + /// - SOCIAL_NETWORK, + /// - SOCIAL_ACTION, + /// - SOCIAL_ACTION_TARGET, + pub field: String, +} + +impl Part for FilterExpression {} + + +/// A conversion path dimension value, containing a list of interactions with their attributes. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfDataRowsConversionPathValue { + /// Node value of an interaction on conversion path. Such as source, medium etc. + #[serde(alias="nodeValue")] + pub node_value: String, + /// Type of an interaction on conversion path. Such as CLICK, IMPRESSION etc. + #[serde(alias="interactionType")] + pub interaction_type: String, +} + +impl NestedType for McfDataRowsConversionPathValue {} +impl Part for McfDataRowsConversionPathValue {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataDataTableRows { + /// no description provided + pub c: Vec, +} + +impl NestedType for GaDataDataTableRows {} +impl Part for GaDataDataTableRows {} + + +/// JSON template for an AdWords account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdWordsAccount { + /// Resource type for AdWords account. + pub kind: String, + /// Customer ID. This field is required when creating an AdWords link. + #[serde(alias="customerId")] + pub customer_id: String, + /// True if auto-tagging is enabled on the AdWords account. Read-only after the insert operation. + #[serde(alias="autoTaggingEnabled")] + pub auto_tagging_enabled: bool, +} + +impl Part for AdWordsAccount {} + + +/// JSON template for a web property reference. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WebPropertyRef { + /// Analytics web property reference. + pub kind: String, + /// Link for this web property. + pub href: String, + /// Name of this web property. + pub name: String, + /// Account ID to which this web property belongs. + #[serde(alias="accountId")] + pub account_id: String, + /// Internal ID for this web property. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: String, + /// Web property ID of the form UA-XXXXX-YY. + pub id: String, +} + +impl Part for WebPropertyRef {} + + +/// Child link for this web property. Points to the list of views (profiles) for this web property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WebpropertyChildLink { + /// Link to the list of views (profiles) for this web property. + pub href: String, + /// Type of the parent link. Its value is "analytics#profiles". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for WebpropertyChildLink {} +impl Part for WebpropertyChildLink {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataDataTableRowsC { + /// no description provided + pub v: String, +} + +impl NestedType for GaDataDataTableRowsC {} +impl Part for GaDataDataTableRowsC {} + + +/// JSON template for a metadata column. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Column { + /// Map of attribute name and value for this column. + pub attributes: HashMap, + /// Resource type for Analytics column. + pub kind: String, + /// Column id. + pub id: String, +} + +impl Part for Column {} + + +/// A profile filter link collection lists profile filter links between profiles and filters. Each resource in the collection corresponds to a profile filter link. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [profile filter links list management](struct.ManagementProfileFilterLinkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProfileFilterLinks { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of profile filter links. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1,000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this profile filter link collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this profile filter link collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for ProfileFilterLinks {} + + +/// JSON template for an Analytics account filter. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [filters delete management](struct.ManagementFilterDeleteCall.html) (response) +/// * [filters patch management](struct.ManagementFilterPatchCall.html) (request|response) +/// * [filters update management](struct.ManagementFilterUpdateCall.html) (request|response) +/// * [filters get management](struct.ManagementFilterGetCall.html) (response) +/// * [filters insert management](struct.ManagementFilterInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Filter { + /// Resource type for Analytics filter. + pub kind: Option, + /// Name of this filter. + pub name: Option, + /// Time this filter was created. + pub created: Option, + /// Time this filter was last modified. + pub updated: Option, + /// Details for the filter of the type ADVANCED. + #[serde(alias="advancedDetails")] + pub advanced_details: Option, + /// Details for the filter of the type LOWER. + #[serde(alias="lowercaseDetails")] + pub lowercase_details: Option, + /// Parent link for this filter. Points to the account to which this filter belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Details for the filter of the type EXCLUDE. + #[serde(alias="excludeDetails")] + pub exclude_details: Option, + /// Details for the filter of the type INCLUDE. + #[serde(alias="includeDetails")] + pub include_details: Option, + /// Details for the filter of the type UPPER. + #[serde(alias="uppercaseDetails")] + pub uppercase_details: Option, + /// Account ID to which this filter belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// Type of this filter. Possible values are INCLUDE, EXCLUDE, LOWERCASE, UPPERCASE, SEARCH_AND_REPLACE and ADVANCED. + #[serde(alias="type")] + pub type_: Option, + /// Filter ID. + pub id: Option, + /// Link for this filter. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Details for the filter of the type SEARCH_AND_REPLACE. + #[serde(alias="searchAndReplaceDetails")] + pub search_and_replace_details: Option, +} + +impl RequestValue for Filter {} +impl ResponseResult for Filter {} + + +/// JSON template for Analytics Entity AdWords Link. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [web property ad words links update management](struct.ManagementWebPropertyAdWordsLinkUpdateCall.html) (request|response) +/// * [web property ad words links patch management](struct.ManagementWebPropertyAdWordsLinkPatchCall.html) (request|response) +/// * [web property ad words links insert management](struct.ManagementWebPropertyAdWordsLinkInsertCall.html) (request|response) +/// * [web property ad words links get management](struct.ManagementWebPropertyAdWordsLinkGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EntityAdWordsLink { + /// Resource type for entity AdWords link. + pub kind: Option, + /// Name of the link. This field is required when creating an AdWords link. + pub name: Option, + /// A list of AdWords client accounts. These cannot be MCC accounts. This field is required when creating an AdWords link. It cannot be empty. + #[serde(alias="adWordsAccounts")] + pub ad_words_accounts: Option>, + /// IDs of linked Views (Profiles) represented as strings. + #[serde(alias="profileIds")] + pub profile_ids: Option>, + /// Entity AdWords link ID + pub id: Option, + /// URL link for this Google Analytics - Google AdWords link. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Web property being linked. + pub entity: Option, +} + +impl RequestValue for EntityAdWordsLink {} +impl ResponseResult for EntityAdWordsLink {} + + +/// Upload collection lists Analytics uploads to which the user has access. Each custom data source can have a set of uploads. Each resource in the upload collection corresponds to a single Analytics data upload. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [uploads list management](struct.ManagementUploadListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Uploads { + /// Collection type. + pub kind: String, + /// The total number of results for the query, regardless of the number of resources in the result. + #[serde(alias="totalResults")] + pub total_results: i32, + /// A list of uploads. + pub items: Vec, + /// Link to previous page for this upload collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this upload collection. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for Uploads {} + + +/// Details for the filter of the type LOWER. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterLowercaseDetails { + /// Field to use in the filter. + pub field: String, +} + +impl NestedType for FilterLowercaseDetails {} +impl Part for FilterLowercaseDetails {} + + +/// List of event conditions. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalEventDetailsEventConditions { + /// Expression used for this match. + pub expression: String, + /// Type of the match to be performed. Possible values are REGEXP, BEGINS_WITH, or EXACT. + #[serde(alias="matchType")] + pub match_type: String, + /// Type of this event condition. Possible values are CATEGORY, ACTION, LABEL, or VALUE. + #[serde(alias="type")] + pub type_: String, + /// Type of comparison. Possible values are LESS_THAN, GREATER_THAN or EQUAL. + #[serde(alias="comparisonType")] + pub comparison_type: String, + /// Value used for this comparison. + #[serde(alias="comparisonValue")] + pub comparison_value: String, +} + +impl NestedType for GoalEventDetailsEventConditions {} +impl Part for GoalEventDetailsEventConditions {} + + +/// List of steps configured for this goal funnel. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalUrlDestinationDetailsSteps { + /// URL for this step. + pub url: String, + /// Step name. + pub name: String, + /// Step number. + pub number: i32, +} + +impl NestedType for GoalUrlDestinationDetailsSteps {} +impl Part for GoalUrlDestinationDetailsSteps {} + + +/// Parent link for the custom metric. Points to the property to which the custom metric belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomMetricParentLink { + /// Link to the property to which the custom metric belongs. + pub href: String, + /// Type of the parent link. Set to "analytics#webproperty". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for CustomMetricParentLink {} +impl Part for CustomMetricParentLink {} + + +/// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfDataColumnHeaders { + /// Data type. Dimension and metric values data types such as INTEGER, DOUBLE, CURRENCY, MCF_SEQUENCE etc. + #[serde(alias="dataType")] + pub data_type: String, + /// Column Type. Either DIMENSION or METRIC. + #[serde(alias="columnType")] + pub column_type: String, + /// Column name. + pub name: String, +} + +impl NestedType for McfDataColumnHeaders {} +impl Part for McfDataColumnHeaders {} + + +/// Parent link for a goal. Points to the view (profile) to which this goal belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalParentLink { + /// Link to the view (profile) to which this goal belongs. + pub href: String, + /// Value is "analytics#profile". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for GoalParentLink {} +impl Part for GoalParentLink {} + + +/// An entity AdWords link collection provides a list of GA-AdWords links Each resource in this collection corresponds to a single link. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [web property ad words links list management](struct.ManagementWebPropertyAdWordsLinkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EntityAdWordsLinks { + /// Collection type. + pub kind: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// A list of entity AdWords links. + pub items: Vec, + /// Previous link for this AdWords link collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The maximum number of entries the response can contain, regardless of the actual number of entries returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// The starting index of the entries, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Next link for this AdWords link collection. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for EntityAdWordsLinks {} + + +/// Entity for this link. It can be an account, a web property, or a view (profile). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EntityUserLinkEntity { + /// Account for this link. + #[serde(alias="accountRef")] + pub account_ref: AccountRef, + /// View (Profile) for this link. + #[serde(alias="profileRef")] + pub profile_ref: ProfileRef, + /// Web property for this link. + #[serde(alias="webPropertyRef")] + pub web_property_ref: WebPropertyRef, +} + +impl NestedType for EntityUserLinkEntity {} +impl Part for EntityUserLinkEntity {} + + +/// JSON template for a linked account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountRef { + /// Analytics account reference. + pub kind: String, + /// Link for this account. + pub href: String, + /// Account ID. + pub id: String, + /// Account name. + pub name: String, +} + +impl Part for AccountRef {} + + +/// An entity user link collection provides a list of Analytics ACL links Each resource in this collection corresponds to a single link. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [account user links list management](struct.ManagementAccountUserLinkListCall.html) (response) +/// * [webproperty user links list management](struct.ManagementWebpropertyUserLinkListCall.html) (response) +/// * [profile user links list management](struct.ManagementProfileUserLinkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EntityUserLinks { + /// Collection type. + pub kind: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, + /// A list of entity user links. + pub items: Vec, + /// Previous link for this account collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The maximum number of entries the response can contain, regardless of the actual number of entries returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// The starting index of the entries, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Next link for this account collection. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for EntityUserLinks {} + + +/// An segment collection lists Analytics segments that the user has access to. Each resource in the collection corresponds to a single Analytics segment. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [segments list management](struct.ManagementSegmentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Segments { + /// Email ID of the authenticated user + pub username: String, + /// Collection type for segments. + pub kind: String, + /// A list of segments. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this segment collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this segment collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Segments {} + + +/// Child link for an account entry. Points to the list of web properties for this account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountChildLink { + /// Link to the list of web properties for this account. + pub href: String, + /// Type of the child link. Its value is "analytics#webproperties". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for AccountChildLink {} +impl Part for AccountChildLink {} + + +/// Details for the filter of the type UPPER. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterUppercaseDetails { + /// Field to use in the filter. + pub field: String, +} + +impl NestedType for FilterUppercaseDetails {} +impl Part for FilterUppercaseDetails {} + + +/// A union object representing a dimension or metric value. Only one of "primitiveValue" or "conversionPathValue" attribute will be populated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfDataRows { + /// A primitive dimension value. A primitive metric value. + #[serde(alias="primitiveValue")] + pub primitive_value: String, + /// A conversion path dimension value, containing a list of interactions with their attributes. + #[serde(alias="conversionPathValue")] + pub conversion_path_value: Vec, +} + +impl NestedType for McfDataRows {} +impl Part for McfDataRows {} + + +/// JSON template for an Analytics ProfileSummary. ProfileSummary returns basic information (i.e., summary) for a profile. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProfileSummary { + /// Resource type for Analytics ProfileSummary. + pub kind: String, + /// View (Profile) type. Supported types: WEB or APP. + #[serde(alias="type")] + pub type_: String, + /// View (profile) ID. + pub id: String, + /// View (profile) name. + pub name: String, +} + +impl Part for ProfileSummary {} + + +/// JSON template for Analytics Custom Dimension. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custom dimensions insert management](struct.ManagementCustomDimensionInsertCall.html) (request|response) +/// * [custom dimensions patch management](struct.ManagementCustomDimensionPatchCall.html) (request|response) +/// * [custom dimensions update management](struct.ManagementCustomDimensionUpdateCall.html) (request|response) +/// * [custom dimensions get management](struct.ManagementCustomDimensionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomDimension { + /// Index of the custom dimension. + pub index: Option, + /// Kind value for a custom dimension. Set to "analytics#customDimension". It is a read-only field. + pub kind: Option, + /// Name of the custom dimension. + pub name: Option, + /// Time the custom dimension was created. + pub created: Option, + /// Time the custom dimension was last modified. + pub updated: Option, + /// Property ID. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// Boolean indicating whether the custom dimension is active. + pub active: Option, + /// Scope of the custom dimension: HIT, SESSION, USER or PRODUCT. + pub scope: Option, + /// Parent link for the custom dimension. Points to the property to which the custom dimension belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Custom dimension ID. + pub id: Option, + /// Link for the custom dimension + #[serde(alias="selfLink")] + pub self_link: Option, + /// Account ID. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for CustomDimension {} +impl ResponseResult for CustomDimension {} + + +/// Permissions the user has for this view (profile). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProfilePermissions { + /// All the permissions that the user has for this view (profile). These include any implied permissions (e.g., EDIT implies VIEW) or inherited permissions from the parent web property. + pub effective: Vec, +} + +impl NestedType for ProfilePermissions {} +impl Part for ProfilePermissions {} + + +/// Array of variations. The first variation in the array is the original. The number of variations may not change once an experiment is in the RUNNING state. At least two variations are required before status can be set to RUNNING. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExperimentVariations { + /// Status of the variation. Possible values: "ACTIVE", "INACTIVE". INACTIVE variations are not served. This field may not be changed for an experiment whose status is ENDED. + pub status: String, + /// The URL of the variation. This field may not be changed for an experiment whose status is RUNNING or ENDED. + pub url: String, + /// True if the experiment has ended and this variation performed (statistically) significantly better than the original. This field is read-only. + pub won: bool, + /// The name of the variation. This field is required when creating an experiment. This field may not be changed for an experiment whose status is ENDED. + pub name: String, + /// Weight that this variation should receive. Only present if the experiment is running. This field is read-only. + pub weight: f64, +} + +impl NestedType for ExperimentVariations {} +impl Part for ExperimentVariations {} + + +/// JSON template for an Analytics segment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Segment { + /// Segment definition. + pub definition: String, + /// Resource type for Analytics segment. + pub kind: String, + /// Segment ID. Can be used with the 'segment' parameter in Core Reporting API. + #[serde(alias="segmentId")] + pub segment_id: String, + /// Time the segment was created. + pub created: String, + /// Time the segment was last modified. + pub updated: String, + /// Type for a segment. Possible values are "BUILT_IN" or "CUSTOM". + #[serde(alias="type")] + pub type_: String, + /// Segment ID. + pub id: String, + /// Link for this segment. + #[serde(alias="selfLink")] + pub self_link: String, + /// Segment name. + pub name: String, +} + +impl Part for Segment {} + + +/// Analytics data request query parameters. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct McfDataQuery { + /// Maximum results per page. + #[serde(alias="max-results")] + pub max_results: i32, + /// List of dimensions or metrics based on which Analytics data is sorted. + pub sort: Vec, + /// List of analytics dimensions. + pub dimensions: String, + /// Start date. + #[serde(alias="start-date")] + pub start_date: String, + /// Start index. + #[serde(alias="start-index")] + pub start_index: i32, + /// End date. + #[serde(alias="end-date")] + pub end_date: String, + /// Unique table ID. + pub ids: String, + /// List of analytics metrics. + pub metrics: Vec, + /// Desired sampling level + #[serde(alias="samplingLevel")] + pub sampling_level: String, + /// Comma-separated list of dimension or metric filters. + pub filters: String, + /// Analytics advanced segment. + pub segment: String, +} + +impl NestedType for McfDataQuery {} +impl Part for McfDataQuery {} + + +/// JSON template for an Analytics view (profile). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [profiles insert management](struct.ManagementProfileInsertCall.html) (request|response) +/// * [profiles update management](struct.ManagementProfileUpdateCall.html) (request|response) +/// * [profiles get management](struct.ManagementProfileGetCall.html) (response) +/// * [profiles patch management](struct.ManagementProfilePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Profile { + /// Time this view (profile) was last modified. + pub updated: Option, + /// The query parameters that are excluded from this view (profile). + #[serde(alias="excludeQueryParameters")] + pub exclude_query_parameters: Option, + /// The currency type associated with this view (profile). The supported values are: + /// ARS, AUD, BGN, BRL, CAD, CHF, CNY, CZK, DKK, EUR, GBP, HKD, HUF, IDR, INR, JPY, KRW, LTL, MXN, NOK, NZD, PHP, PLN, RUB, SEK, THB, TRY, TWD, USD, VND, ZAR + pub currency: Option, + /// Internal ID for the web property to which this view (profile) belongs. + #[serde(alias="internalWebPropertyId")] + pub internal_web_property_id: Option, + /// Child link for this view (profile). Points to the list of goals for this view (profile). + #[serde(alias="childLink")] + pub child_link: Option, + /// Indicates whether enhanced ecommerce tracking is enabled for this view (profile). This property can only be enabled if ecommerce tracking is enabled. + #[serde(alias="enhancedECommerceTracking")] + pub enhanced_e_commerce_tracking: Option, + /// Indicates whether ecommerce tracking is enabled for this view (profile). + #[serde(alias="eCommerceTracking")] + pub e_commerce_tracking: Option, + /// Web property ID of the form UA-XXXXX-YY to which this view (profile) belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: Option, + /// Time zone for which this view (profile) has been configured. Time zones are identified by strings from the TZ database. + pub timezone: Option, + /// View (Profile) ID. + pub id: Option, + /// Account ID to which this view (profile) belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// Default page for this view (profile). + #[serde(alias="defaultPage")] + pub default_page: Option, + /// Resource type for Analytics view (profile). + pub kind: Option, + /// Whether or not Analytics will strip search query parameters from the URLs in your reports. + #[serde(alias="stripSiteSearchQueryParameters")] + pub strip_site_search_query_parameters: Option, + /// Name of this view (profile). + pub name: Option, + /// Time this view (profile) was created. + pub created: Option, + /// The site search query parameters for this view (profile). + #[serde(alias="siteSearchQueryParameters")] + pub site_search_query_parameters: Option, + /// Website URL for this view (profile). + #[serde(alias="websiteUrl")] + pub website_url: Option, + /// Whether or not Analytics will strip search category parameters from the URLs in your reports. + #[serde(alias="stripSiteSearchCategoryParameters")] + pub strip_site_search_category_parameters: Option, + /// Site search category parameters for this view (profile). + #[serde(alias="siteSearchCategoryParameters")] + pub site_search_category_parameters: Option, + /// Parent link for this view (profile). Points to the web property to which this view (profile) belongs. + #[serde(alias="parentLink")] + pub parent_link: Option, + /// Permissions the user has for this view (profile). + pub permissions: Option, + /// View (Profile) type. Supported types: WEB or APP. + #[serde(alias="type")] + pub type_: Option, + /// Link for this view (profile). + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Profile {} +impl ResponseResult for Profile {} + + +/// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataColumnHeaders { + /// Data type. Dimension column headers have only STRING as the data type. Metric column headers have data types for metric values such as INTEGER, DOUBLE, CURRENCY etc. + #[serde(alias="dataType")] + pub data_type: String, + /// Column Type. Either DIMENSION or METRIC. + #[serde(alias="columnType")] + pub column_type: String, + /// Column name. + pub name: String, +} + +impl NestedType for GaDataColumnHeaders {} +impl Part for GaDataColumnHeaders {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GaDataDataTableCols { + /// no description provided + #[serde(alias="type")] + pub type_: String, + /// no description provided + pub id: String, + /// no description provided + pub label: String, +} + +impl NestedType for GaDataDataTableCols {} +impl Part for GaDataDataTableCols {} + + +/// Details for the goal of the type VISIT_NUM_PAGES. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoalVisitNumPagesDetails { + /// Type of comparison. Possible values are LESS_THAN, GREATER_THAN, or EQUAL. + #[serde(alias="comparisonType")] + pub comparison_type: String, + /// Value used for this comparison. + #[serde(alias="comparisonValue")] + pub comparison_value: String, +} + +impl NestedType for GoalVisitNumPagesDetails {} +impl Part for GoalVisitNumPagesDetails {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomDataSourceChildLink { + /// Link to the list of daily uploads for this custom data source. Link to the list of uploads for this custom data source. + pub href: String, + /// Value is "analytics#dailyUploads". Value is "analytics#uploads". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for CustomDataSourceChildLink {} +impl Part for CustomDataSourceChildLink {} + + +/// An unsampled report collection lists Analytics unsampled reports to which the user has access. Each view (profile) can have a set of unsampled reports. Each resource in the unsampled report collection corresponds to a single Analytics unsampled report. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [unsampled reports list management](struct.ManagementUnsampledReportListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UnsampledReports { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of unsampled reports. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this unsampled report collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this unsampled report collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of resources in the result. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for UnsampledReports {} + + +/// Column headers that list dimension names followed by the metric names. The order of dimensions and metrics is same as specified in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RealtimeDataColumnHeaders { + /// Data type. Dimension column headers have only STRING as the data type. Metric column headers have data types for metric values such as INTEGER, DOUBLE, CURRENCY etc. + #[serde(alias="dataType")] + pub data_type: String, + /// Column Type. Either DIMENSION or METRIC. + #[serde(alias="columnType")] + pub column_type: String, + /// Column name. + pub name: String, +} + +impl NestedType for RealtimeDataColumnHeaders {} +impl Part for RealtimeDataColumnHeaders {} + + +/// Web property being linked. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EntityAdWordsLinkEntity { + /// no description provided + #[serde(alias="webPropertyRef")] + pub web_property_ref: WebPropertyRef, +} + +impl NestedType for EntityAdWordsLinkEntity {} +impl Part for EntityAdWordsLinkEntity {} + + +/// Parent link for this custom data source. Points to the web property to which this custom data source belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomDataSourceParentLink { + /// Link to the web property to which this custom data source belongs. + pub href: String, + /// Value is "analytics#webproperty". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for CustomDataSourceParentLink {} +impl Part for CustomDataSourceParentLink {} + + +/// JSON template for an Analytics custom data source. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomDataSource { + /// Resource type for Analytics custom data source. + pub kind: String, + /// Description of custom data source. + pub description: String, + /// IDs of views (profiles) linked to the custom data source. + #[serde(alias="profilesLinked")] + pub profiles_linked: Vec, + /// no description provided + #[serde(alias="uploadType")] + pub upload_type: String, + /// Time this custom data source was created. + pub created: String, + /// Time this custom data source was last modified. + pub updated: String, + /// Account ID to which this custom data source belongs. + #[serde(alias="accountId")] + pub account_id: String, + /// no description provided + #[serde(alias="childLink")] + pub child_link: CustomDataSourceChildLink, + /// Web property ID of the form UA-XXXXX-YY to which this custom data source belongs. + #[serde(alias="webPropertyId")] + pub web_property_id: String, + /// Parent link for this custom data source. Points to the web property to which this custom data source belongs. + #[serde(alias="parentLink")] + pub parent_link: CustomDataSourceParentLink, + /// no description provided + #[serde(alias="importBehavior")] + pub import_behavior: String, + /// Type of the custom data source. + #[serde(alias="type")] + pub type_: String, + /// Custom data source ID. + pub id: String, + /// Link for this Analytics custom data source. + #[serde(alias="selfLink")] + pub self_link: String, + /// Name of this custom data source. + pub name: String, +} + +impl Part for CustomDataSource {} + + +/// Parent link for the custom dimension. Points to the property to which the custom dimension belongs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomDimensionParentLink { + /// Link to the property to which the custom dimension belongs. + pub href: String, + /// Type of the parent link. Set to "analytics#webproperty". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for CustomDimensionParentLink {} +impl Part for CustomDimensionParentLink {} + + +/// An experiment collection lists Analytics experiments to which the user has access. Each view (profile) can have a set of experiments. Each resource in the Experiment collection corresponds to a single Analytics experiment. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [experiments list management](struct.ManagementExperimentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Experiments { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of experiments. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this experiment collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this experiment collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of resources in the result. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Experiments {} + + +/// A filter collection lists filters created by users in an Analytics account. Each resource in the collection corresponds to a filter. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [filters list management](struct.ManagementFilterListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Filters { + /// Email ID of the authenticated user + pub username: String, + /// Collection type. + pub kind: String, + /// A list of filters. + pub items: Vec, + /// The maximum number of resources the response can contain, regardless of the actual number of resources returned. Its value ranges from 1 to 1,000 with a value of 1000 by default, or otherwise specified by the max-results query parameter. + #[serde(alias="itemsPerPage")] + pub items_per_page: i32, + /// Link to previous page for this filter collection. + #[serde(alias="previousLink")] + pub previous_link: String, + /// The starting index of the resources, which is 1 by default or otherwise specified by the start-index query parameter. + #[serde(alias="startIndex")] + pub start_index: i32, + /// Link to next page for this filter collection. + #[serde(alias="nextLink")] + pub next_link: String, + /// The total number of results for the query, regardless of the number of results in the response. + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl ResponseResult for Filters {} + + +/// Child link for this view (profile). Points to the list of goals for this view (profile). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProfileChildLink { + /// Link to the list of goals for this view (profile). + pub href: String, + /// Value is "analytics#goals". + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for ProfileChildLink {} +impl Part for ProfileChildLink {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *management* resources. +/// It is not used directly, but through the `Analytics` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-analytics3" as analytics3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use analytics3::Analytics; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `account_summaries_list(...)`, `account_user_links_delete(...)`, `account_user_links_insert(...)`, `account_user_links_list(...)`, `account_user_links_update(...)`, `accounts_list(...)`, `custom_data_sources_list(...)`, `custom_dimensions_get(...)`, `custom_dimensions_insert(...)`, `custom_dimensions_list(...)`, `custom_dimensions_patch(...)`, `custom_dimensions_update(...)`, `custom_metrics_get(...)`, `custom_metrics_insert(...)`, `custom_metrics_list(...)`, `custom_metrics_patch(...)`, `custom_metrics_update(...)`, `experiments_delete(...)`, `experiments_get(...)`, `experiments_insert(...)`, `experiments_list(...)`, `experiments_patch(...)`, `experiments_update(...)`, `filters_delete(...)`, `filters_get(...)`, `filters_insert(...)`, `filters_list(...)`, `filters_patch(...)`, `filters_update(...)`, `goals_get(...)`, `goals_insert(...)`, `goals_list(...)`, `goals_patch(...)`, `goals_update(...)`, `profile_filter_links_delete(...)`, `profile_filter_links_get(...)`, `profile_filter_links_insert(...)`, `profile_filter_links_list(...)`, `profile_filter_links_patch(...)`, `profile_filter_links_update(...)`, `profile_user_links_delete(...)`, `profile_user_links_insert(...)`, `profile_user_links_list(...)`, `profile_user_links_update(...)`, `profiles_delete(...)`, `profiles_get(...)`, `profiles_insert(...)`, `profiles_list(...)`, `profiles_patch(...)`, `profiles_update(...)`, `segments_list(...)`, `unsampled_reports_get(...)`, `unsampled_reports_insert(...)`, `unsampled_reports_list(...)`, `uploads_delete_upload_data(...)`, `uploads_get(...)`, `uploads_list(...)`, `uploads_upload_data(...)`, `web_property_ad_words_links_delete(...)`, `web_property_ad_words_links_get(...)`, `web_property_ad_words_links_insert(...)`, `web_property_ad_words_links_list(...)`, `web_property_ad_words_links_patch(...)`, `web_property_ad_words_links_update(...)`, `webproperties_get(...)`, `webproperties_insert(...)`, `webproperties_list(...)`, `webproperties_patch(...)`, `webproperties_update(...)`, `webproperty_user_links_delete(...)`, `webproperty_user_links_insert(...)`, `webproperty_user_links_list(...)` and `webproperty_user_links_update(...)` +/// // to build up your call. +/// let rb = hub.management(); +/// # } +/// ``` +pub struct ManagementMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ManagementMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Create a new property if the account has fewer than 20 properties. Web properties are visible in the Google Analytics interface only if they have at least one profile. + pub fn webproperties_insert(&self, request: &Webproperty, account_id: &str) -> ManagementWebpropertyInsertCall<'a, C, NC, A> { + ManagementWebpropertyInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a view (profile) to which the user has access. + pub fn profiles_get(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileGetCall<'a, C, NC, A> { + ManagementProfileGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all accounts to which the user has access. + pub fn accounts_list(&self) -> ManagementAccountListCall<'a, C, NC, A> { + ManagementAccountListCall { + hub: self.hub, + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update an existing profile filter link. This method supports patch semantics. + pub fn profile_filter_links_patch(&self, request: &ProfileFilterLink, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + ManagementProfileFilterLinkPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a user from the given web property. + pub fn webproperty_user_links_delete(&self, account_id: &str, web_property_id: &str, link_id: &str) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> { + ManagementWebpropertyUserLinkDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a user from the given view (profile). + pub fn profile_user_links_delete(&self, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + ManagementProfileUserLinkDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates permissions for an existing user on the given view (profile). + pub fn profile_user_links_update(&self, request: &EntityUserLink, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + ManagementProfileUserLinkUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new filter. + pub fn filters_insert(&self, request: &Filter, account_id: &str) -> ManagementFilterInsertCall<'a, C, NC, A> { + ManagementFilterInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates permissions for an existing user on the given account. + pub fn account_user_links_update(&self, request: &EntityUserLink, account_id: &str, link_id: &str) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> { + ManagementAccountUserLinkUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing web property. + pub fn webproperties_update(&self, request: &Webproperty, account_id: &str, web_property_id: &str) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> { + ManagementWebpropertyUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates permissions for an existing user on the given web property. + pub fn webproperty_user_links_update(&self, request: &EntityUserLink, account_id: &str, web_property_id: &str, link_id: &str) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + ManagementWebpropertyUserLinkUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new unsampled report. + pub fn unsampled_reports_insert(&self, request: &UnsampledReport, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + ManagementUnsampledReportInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get a custom metric to which the user has access. + pub fn custom_metrics_get(&self, account_id: &str, web_property_id: &str, custom_metric_id: &str) -> ManagementCustomMetricGetCall<'a, C, NC, A> { + ManagementCustomMetricGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_metric_id: custom_metric_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List uploads to which the user has access. + pub fn uploads_get(&self, account_id: &str, web_property_id: &str, custom_data_source_id: &str, upload_id: &str) -> ManagementUploadGetCall<'a, C, NC, A> { + ManagementUploadGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_data_source_id: custom_data_source_id.to_string(), + _upload_id: upload_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a web property-AdWords link to which the user has access. + pub fn web_property_ad_words_links_get(&self, account_id: &str, web_property_id: &str, web_property_ad_words_link_id: &str) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _web_property_ad_words_link_id: web_property_ad_words_link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists webProperty-user links for a given web property. + pub fn webproperty_user_links_list(&self, account_id: &str, web_property_id: &str) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + ManagementWebpropertyUserLinkListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update an existing profile filter link. + pub fn profile_filter_links_update(&self, request: &ProfileFilterLink, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + ManagementProfileFilterLinkUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns an experiment to which the user has access. + pub fn experiments_get(&self, account_id: &str, web_property_id: &str, profile_id: &str, experiment_id: &str) -> ManagementExperimentGetCall<'a, C, NC, A> { + ManagementExperimentGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _experiment_id: experiment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing custom dimension. + pub fn custom_dimensions_update(&self, request: &CustomDimension, account_id: &str, web_property_id: &str, custom_dimension_id: &str) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + ManagementCustomDimensionUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_dimension_id: custom_dimension_id.to_string(), + _ignore_custom_data_source_links: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a single unsampled report. + pub fn unsampled_reports_get(&self, account_id: &str, web_property_id: &str, profile_id: &str, unsampled_report_id: &str) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + ManagementUnsampledReportGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _unsampled_report_id: unsampled_report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new profile filter link. + pub fn profile_filter_links_insert(&self, request: &ProfileFilterLink, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + ManagementProfileFilterLinkInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing filter. + pub fn filters_update(&self, request: &Filter, account_id: &str, filter_id: &str) -> ManagementFilterUpdateCall<'a, C, NC, A> { + ManagementFilterUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _filter_id: filter_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a profile filter link. + pub fn profile_filter_links_delete(&self, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + ManagementProfileFilterLinkDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists segments to which the user has access. + pub fn segments_list(&self) -> ManagementSegmentListCall<'a, C, NC, A> { + ManagementSegmentListCall { + hub: self.hub, + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a view (profile). + pub fn profiles_delete(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileDeleteCall<'a, C, NC, A> { + ManagementProfileDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing view (profile). This method supports patch semantics. + pub fn goals_patch(&self, request: &Goal, account_id: &str, web_property_id: &str, profile_id: &str, goal_id: &str) -> ManagementGoalPatchCall<'a, C, NC, A> { + ManagementGoalPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _goal_id: goal_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing custom dimension. This method supports patch semantics. + pub fn custom_dimensions_patch(&self, request: &CustomDimension, account_id: &str, web_property_id: &str, custom_dimension_id: &str) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + ManagementCustomDimensionPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_dimension_id: custom_dimension_id.to_string(), + _ignore_custom_data_source_links: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update an existing experiment. This method supports patch semantics. + pub fn experiments_patch(&self, request: &Experiment, account_id: &str, web_property_id: &str, profile_id: &str, experiment_id: &str) -> ManagementExperimentPatchCall<'a, C, NC, A> { + ManagementExperimentPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _experiment_id: experiment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists experiments to which the user has access. + pub fn experiments_list(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementExperimentListCall<'a, C, NC, A> { + ManagementExperimentListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists views (profiles) to which the user has access. + pub fn profiles_list(&self, account_id: &str, web_property_id: &str) -> ManagementProfileListCall<'a, C, NC, A> { + ManagementProfileListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists goals to which the user has access. + pub fn goals_list(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementGoalListCall<'a, C, NC, A> { + ManagementGoalListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new goal. + pub fn goals_insert(&self, request: &Goal, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementGoalInsertCall<'a, C, NC, A> { + ManagementGoalInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing custom metric. This method supports patch semantics. + pub fn custom_metrics_patch(&self, request: &CustomMetric, account_id: &str, web_property_id: &str, custom_metric_id: &str) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + ManagementCustomMetricPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_metric_id: custom_metric_id.to_string(), + _ignore_custom_data_source_links: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Upload data for a custom data source. + pub fn uploads_upload_data(&self, account_id: &str, web_property_id: &str, custom_data_source_id: &str) -> ManagementUploadUploadDataCall<'a, C, NC, A> { + ManagementUploadUploadDataCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_data_source_id: custom_data_source_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a new user to the given account. + pub fn account_user_links_insert(&self, request: &EntityUserLink, account_id: &str) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> { + ManagementAccountUserLinkInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a new user to the given web property. + pub fn webproperty_user_links_insert(&self, request: &EntityUserLink, account_id: &str, web_property_id: &str) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> { + ManagementWebpropertyUserLinkInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete an experiment. + pub fn experiments_delete(&self, account_id: &str, web_property_id: &str, profile_id: &str, experiment_id: &str) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + ManagementExperimentDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _experiment_id: experiment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing view (profile). This method supports patch semantics. + pub fn profiles_patch(&self, request: &Profile, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfilePatchCall<'a, C, NC, A> { + ManagementProfilePatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a filters to which the user has access. + pub fn filters_get(&self, account_id: &str, filter_id: &str) -> ManagementFilterGetCall<'a, C, NC, A> { + ManagementFilterGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _filter_id: filter_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists webProperty-AdWords links for a given web property. + pub fn web_property_ad_words_links_list(&self, account_id: &str, web_property_id: &str) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists account summaries (lightweight tree comprised of accounts/properties/profiles) to which the user has access. + pub fn account_summaries_list(&self) -> ManagementAccountSummaryListCall<'a, C, NC, A> { + ManagementAccountSummaryListCall { + hub: self.hub, + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists custom dimensions to which the user has access. + pub fn custom_dimensions_list(&self, account_id: &str, web_property_id: &str) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + ManagementCustomDimensionListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List uploads to which the user has access. + pub fn uploads_list(&self, account_id: &str, web_property_id: &str, custom_data_source_id: &str) -> ManagementUploadListCall<'a, C, NC, A> { + ManagementUploadListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_data_source_id: custom_data_source_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists profile-user links for a given view (profile). + pub fn profile_user_links_list(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + ManagementProfileUserLinkListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists account-user links for a given account. + pub fn account_user_links_list(&self, account_id: &str) -> ManagementAccountUserLinkListCall<'a, C, NC, A> { + ManagementAccountUserLinkListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing custom metric. + pub fn custom_metrics_update(&self, request: &CustomMetric, account_id: &str, web_property_id: &str, custom_metric_id: &str) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + ManagementCustomMetricUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_metric_id: custom_metric_id.to_string(), + _ignore_custom_data_source_links: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete data associated with a previous upload. + pub fn uploads_delete_upload_data(&self, request: &AnalyticsDataimportDeleteUploadDataRequest, account_id: &str, web_property_id: &str, custom_data_source_id: &str) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + ManagementUploadDeleteUploadDataCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_data_source_id: custom_data_source_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update an existing experiment. + pub fn experiments_update(&self, request: &Experiment, account_id: &str, web_property_id: &str, profile_id: &str, experiment_id: &str) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + ManagementExperimentUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _experiment_id: experiment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing view (profile). + pub fn goals_update(&self, request: &Goal, account_id: &str, web_property_id: &str, profile_id: &str, goal_id: &str) -> ManagementGoalUpdateCall<'a, C, NC, A> { + ManagementGoalUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _goal_id: goal_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List custom data sources to which the user has access. + pub fn custom_data_sources_list(&self, account_id: &str, web_property_id: &str) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + ManagementCustomDataSourceListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists custom metrics to which the user has access. + pub fn custom_metrics_list(&self, account_id: &str, web_property_id: &str) -> ManagementCustomMetricListCall<'a, C, NC, A> { + ManagementCustomMetricListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists unsampled reports to which the user has access. + pub fn unsampled_reports_list(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + ManagementUnsampledReportListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a web property to which the user has access. + pub fn webproperties_get(&self, account_id: &str, web_property_id: &str) -> ManagementWebpropertyGetCall<'a, C, NC, A> { + ManagementWebpropertyGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new experiment. + pub fn experiments_insert(&self, request: &Experiment, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementExperimentInsertCall<'a, C, NC, A> { + ManagementExperimentInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get a custom dimension to which the user has access. + pub fn custom_dimensions_get(&self, account_id: &str, web_property_id: &str, custom_dimension_id: &str) -> ManagementCustomDimensionGetCall<'a, C, NC, A> { + ManagementCustomDimensionGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _custom_dimension_id: custom_dimension_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all profile filter links for a profile. + pub fn profile_filter_links_list(&self, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + ManagementProfileFilterLinkListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing web property. This method supports patch semantics. + pub fn webproperties_patch(&self, request: &Webproperty, account_id: &str, web_property_id: &str) -> ManagementWebpropertyPatchCall<'a, C, NC, A> { + ManagementWebpropertyPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new custom dimension. + pub fn custom_dimensions_insert(&self, request: &CustomDimension, account_id: &str, web_property_id: &str) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> { + ManagementCustomDimensionInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new custom metric. + pub fn custom_metrics_insert(&self, request: &CustomMetric, account_id: &str, web_property_id: &str) -> ManagementCustomMetricInsertCall<'a, C, NC, A> { + ManagementCustomMetricInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a new user to the given view (profile). + pub fn profile_user_links_insert(&self, request: &EntityUserLink, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + ManagementProfileUserLinkInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists web properties to which the user has access. + pub fn webproperties_list(&self, account_id: &str) -> ManagementWebpropertyListCall<'a, C, NC, A> { + ManagementWebpropertyListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a webProperty-AdWords link. + pub fn web_property_ad_words_links_insert(&self, request: &EntityAdWordsLink, account_id: &str, web_property_id: &str) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing webProperty-AdWords link. This method supports patch semantics. + pub fn web_property_ad_words_links_patch(&self, request: &EntityAdWordsLink, account_id: &str, web_property_id: &str, web_property_ad_words_link_id: &str) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _web_property_ad_words_link_id: web_property_ad_words_link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a goal to which the user has access. + pub fn goals_get(&self, account_id: &str, web_property_id: &str, profile_id: &str, goal_id: &str) -> ManagementGoalGetCall<'a, C, NC, A> { + ManagementGoalGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _goal_id: goal_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a web property-AdWords link. + pub fn web_property_ad_words_links_delete(&self, account_id: &str, web_property_id: &str, web_property_ad_words_link_id: &str) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _web_property_ad_words_link_id: web_property_ad_words_link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing webProperty-AdWords link. + pub fn web_property_ad_words_links_update(&self, request: &EntityAdWordsLink, account_id: &str, web_property_id: &str, web_property_ad_words_link_id: &str) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + ManagementWebPropertyAdWordsLinkUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _web_property_ad_words_link_id: web_property_ad_words_link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing filter. This method supports patch semantics. + pub fn filters_patch(&self, request: &Filter, account_id: &str, filter_id: &str) -> ManagementFilterPatchCall<'a, C, NC, A> { + ManagementFilterPatchCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _filter_id: filter_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all filters for an account + pub fn filters_list(&self, account_id: &str) -> ManagementFilterListCall<'a, C, NC, A> { + ManagementFilterListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a filter. + pub fn filters_delete(&self, account_id: &str, filter_id: &str) -> ManagementFilterDeleteCall<'a, C, NC, A> { + ManagementFilterDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _filter_id: filter_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new view (profile). + pub fn profiles_insert(&self, request: &Profile, account_id: &str, web_property_id: &str) -> ManagementProfileInsertCall<'a, C, NC, A> { + ManagementProfileInsertCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a user from the given account. + pub fn account_user_links_delete(&self, account_id: &str, link_id: &str) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> { + ManagementAccountUserLinkDeleteCall { + hub: self.hub, + _account_id: account_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing view (profile). + pub fn profiles_update(&self, request: &Profile, account_id: &str, web_property_id: &str, profile_id: &str) -> ManagementProfileUpdateCall<'a, C, NC, A> { + ManagementProfileUpdateCall { + hub: self.hub, + _request: request.clone(), + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a single profile filter link. + pub fn profile_filter_links_get(&self, account_id: &str, web_property_id: &str, profile_id: &str, link_id: &str) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + ManagementProfileFilterLinkGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _web_property_id: web_property_id.to_string(), + _profile_id: profile_id.to_string(), + _link_id: link_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *data* resources. +/// It is not used directly, but through the `Analytics` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-analytics3" as analytics3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use analytics3::Analytics; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `ga_get(...)`, `mcf_get(...)` and `realtime_get(...)` +/// // to build up your call. +/// let rb = hub.data(); +/// # } +/// ``` +pub struct DataMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DataMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DataMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns Analytics Multi-Channel Funnels data for a view (profile). + pub fn mcf_get(&self, ids: &str, start_date: &str, end_date: &str, metrics: &str) -> DataMcfGetCall<'a, C, NC, A> { + DataMcfGetCall { + hub: self.hub, + _ids: ids.to_string(), + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _metrics: metrics.to_string(), + _start_index: Default::default(), + _sort: Default::default(), + _sampling_level: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _dimensions: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns Analytics data for a view (profile). + pub fn ga_get(&self, ids: &str, start_date: &str, end_date: &str, metrics: &str) -> DataGaGetCall<'a, C, NC, A> { + DataGaGetCall { + hub: self.hub, + _ids: ids.to_string(), + _start_date: start_date.to_string(), + _end_date: end_date.to_string(), + _metrics: metrics.to_string(), + _start_index: Default::default(), + _sort: Default::default(), + _segment: Default::default(), + _sampling_level: Default::default(), + _output: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _dimensions: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns real time data for a view (profile). + pub fn realtime_get(&self, ids: &str, metrics: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + DataRealtimeGetCall { + hub: self.hub, + _ids: ids.to_string(), + _metrics: metrics.to_string(), + _sort: Default::default(), + _max_results: Default::default(), + _filters: Default::default(), + _dimensions: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *provisioning* resources. +/// It is not used directly, but through the `Analytics` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-analytics3" as analytics3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use analytics3::Analytics; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create_account_ticket(...)` +/// // to build up your call. +/// let rb = hub.provisioning(); +/// # } +/// ``` +pub struct ProvisioningMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProvisioningMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProvisioningMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates an account ticket. + pub fn create_account_ticket(&self, request: &AccountTicket) -> ProvisioningCreateAccountTicketCall<'a, C, NC, A> { + ProvisioningCreateAccountTicketCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *metadata* resources. +/// It is not used directly, but through the `Analytics` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-analytics3" as analytics3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use analytics3::Analytics; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `columns_list(...)` +/// // to build up your call. +/// let rb = hub.metadata(); +/// # } +/// ``` +pub struct MetadataMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MetadataMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetadataMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all columns for a report type + pub fn columns_list(&self, report_type: &str) -> MetadataColumnListCall<'a, C, NC, A> { + MetadataColumnListCall { + hub: self.hub, + _report_type: report_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Create a new property if the account has fewer than 20 properties. Web properties are visible in the Google Analytics interface only if they have at least one profile. +/// +/// A builder for the *webproperties.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Webproperty; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Webproperty = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperties_insert(&req, "accountId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Webproperty, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Webproperty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webproperties.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Webproperty) -> ManagementWebpropertyInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the web property for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a view (profile) to which the user has access. +/// +/// A builder for the *profiles.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_get("accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Profile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve the goal for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the goal for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve the goal for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all accounts to which the user has access. +/// +/// A builder for the *accounts.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().accounts_list() +/// .start_index(-61) +/// .max_results(-95) +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Accounts)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first account to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementAccountListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of accounts to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementAccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update an existing profile filter link. This method supports patch semantics. +/// +/// A builder for the *profileFilterLinks.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::ProfileFilterLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProfileFilterLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_patch(&req, "accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: ProfileFilterLink, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProfileFilterLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProfileFilterLink) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which profile filter link belongs. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id to which profile filter link belongs + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to which filter link belongs + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the profile filter link to be updated. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a user from the given web property. +/// +/// A builder for the *webpropertyUserLinks.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperty_user_links_delete("accountId", "webPropertyId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webpropertyUserLinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["accountId", "webPropertyId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to delete the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID to delete the user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to delete the user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a user from the given view (profile). +/// +/// A builder for the *profileUserLinks.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_user_links_delete("accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileUserLinkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileUserLinkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileUserLinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to delete the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID to delete the user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to delete the user link for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to delete the user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates permissions for an existing user on the given view (profile). +/// +/// A builder for the *profileUserLinks.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_user_links_update(&req, "accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileUserLinkUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileUserLinkUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileUserLinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to update the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID to update the user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile ID) to update the user link for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to update the user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new filter. +/// +/// A builder for the *filters.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Filter; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Filter = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_insert(&req, "accountId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Filter, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filter)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Filter) -> ManagementFilterInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create filter for. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates permissions for an existing user on the given account. +/// +/// A builder for the *accountUserLinks.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().account_user_links_update(&req, "accountId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountUserLinkUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountUserLinkUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accountUserLinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to update the account-user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to update the account-user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing web property. +/// +/// A builder for the *webproperties.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Webproperty; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Webproperty = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperties_update(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Webproperty, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Webproperty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webproperties.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Webproperty) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the web property belongs + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates permissions for an existing user on the given web property. +/// +/// A builder for the *webpropertyUserLinks.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperty_user_links_update(&req, "accountId", "webPropertyId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _web_property_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webpropertyUserLinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to update the account-user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to update the account-user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to update the account-user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyUserLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new unsampled report. +/// +/// A builder for the *unsampledReports.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::UnsampledReport; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UnsampledReport = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().unsampled_reports_insert(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementUnsampledReportInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: UnsampledReport, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUnsampledReportInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUnsampledReportInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UnsampledReport)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.unsampledReports.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UnsampledReport) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the unsampled report for. + pub fn account_id(mut self, new_value: &str) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to create the unsampled report for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to create the unsampled report for. + pub fn profile_id(mut self, new_value: &str) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUnsampledReportInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get a custom metric to which the user has access. +/// +/// A builder for the *customMetrics.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_metrics_get("accountId", "webPropertyId", "customMetricId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomMetricGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _custom_metric_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomMetricGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomMetricGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customMetrics.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customMetricId", self._custom_metric_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "customMetricId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customMetrics/{customMetricId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customMetricId}", "customMetricId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customMetricId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom metric to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomMetricGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom metric to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomMetricGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom metric id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the custom metric to retrieve. + pub fn custom_metric_id(mut self, new_value: &str) -> ManagementCustomMetricGetCall<'a, C, NC, A> { + self._custom_metric_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomMetricGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomMetricGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomMetricGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List uploads to which the user has access. +/// +/// A builder for the *uploads.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().uploads_get("accountId", "webPropertyId", "customDataSourceId", "uploadId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementUploadGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _custom_data_source_id: String, + _upload_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUploadGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUploadGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Upload)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.uploads.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDataSourceId", self._custom_data_source_id.to_string())); + params.push(("uploadId", self._upload_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "customDataSourceId", "uploadId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads/{uploadId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDataSourceId}", "customDataSourceId"), ("{uploadId}", "uploadId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "customDataSourceId", "uploadId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account Id for the upload to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementUploadGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id for the upload to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUploadGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom data source Id for upload to retrieve. + pub fn custom_data_source_id(mut self, new_value: &str) -> ManagementUploadGetCall<'a, C, NC, A> { + self._custom_data_source_id = new_value.to_string(); + self + } + /// Sets the *upload id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Upload Id to retrieve. + pub fn upload_id(mut self, new_value: &str) -> ManagementUploadGetCall<'a, C, NC, A> { + self._upload_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUploadGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUploadGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUploadGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a web property-AdWords link to which the user has access. +/// +/// A builder for the *webPropertyAdWordsLinks.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_get("accountId", "webPropertyId", "webPropertyAdWordsLinkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _web_property_ad_words_link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityAdWordsLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("webPropertyAdWordsLinkId", self._web_property_ad_words_link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks/{webPropertyAdWordsLinkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{webPropertyAdWordsLinkId}", "webPropertyAdWordsLinkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the account which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the AdWords link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *web property ad words link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property-AdWords link ID. + pub fn web_property_ad_words_link_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> { + self._web_property_ad_words_link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists webProperty-user links for a given web property. +/// +/// A builder for the *webpropertyUserLinks.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperty_user_links_list("accountId", "webPropertyId") +/// .start_index(-23) +/// .max_results(-45) +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyUserLinkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyUserLinkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLinks)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webpropertyUserLinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID for the webProperty-user links to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first webProperty-user link to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of webProperty-user Links to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyUserLinkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update an existing profile filter link. +/// +/// A builder for the *profileFilterLinks.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::ProfileFilterLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProfileFilterLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_update(&req, "accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: ProfileFilterLink, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProfileFilterLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProfileFilterLink) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which profile filter link belongs. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id to which profile filter link belongs + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to which filter link belongs + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the profile filter link to be updated. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns an experiment to which the user has access. +/// +/// A builder for the *experiments.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_get("accountId", "webPropertyId", "profileId", "experimentId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _experiment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Experiment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("experimentId", self._experiment_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "experimentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{experimentId}", "experimentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "experimentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve the experiment for. + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the experiment for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve the experiment for. + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *experiment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Experiment ID to retrieve the experiment for. + pub fn experiment_id(mut self, new_value: &str) -> ManagementExperimentGetCall<'a, C, NC, A> { + self._experiment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing custom dimension. +/// +/// A builder for the *customDimensions.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomDimension; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomDimension = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_dimensions_update(&req, "accountId", "webPropertyId", "customDimensionId") +/// .ignore_custom_data_source_links(true) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDimensionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomDimension, + _account_id: String, + _web_property_id: String, + _custom_dimension_id: String, + _ignore_custom_data_source_links: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDimensionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDimensionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDimension)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDimensions.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDimensionId", self._custom_dimension_id.to_string())); + if let Some(value) = self._ignore_custom_data_source_links { + params.push(("ignoreCustomDataSourceLinks", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "customDimensionId", "ignoreCustomDataSourceLinks"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDimensions/{customDimensionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDimensionId}", "customDimensionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDimensionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomDimension) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom dimension to update. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimension to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom dimension id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom dimension ID for the custom dimension to update. + pub fn custom_dimension_id(mut self, new_value: &str) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._custom_dimension_id = new_value.to_string(); + self + } + /// Sets the *ignore custom data source links* query property to the given value. + /// + /// + /// Force the update and ignore any warnings related to the custom dimension being linked to a custom data source / data set. + pub fn ignore_custom_data_source_links(mut self, new_value: bool) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._ignore_custom_data_source_links = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDimensionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a single unsampled report. +/// +/// A builder for the *unsampledReports.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().unsampled_reports_get("accountId", "webPropertyId", "profileId", "unsampledReportId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementUnsampledReportGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _unsampled_report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUnsampledReportGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUnsampledReportGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UnsampledReport)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.unsampledReports.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("unsampledReportId", self._unsampled_report_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "unsampledReportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports/{unsampledReportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{unsampledReportId}", "unsampledReportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "unsampledReportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve unsampled report for. + pub fn account_id(mut self, new_value: &str) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve unsampled reports for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve unsampled report for. + pub fn profile_id(mut self, new_value: &str) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *unsampled report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the unsampled report to retrieve. + pub fn unsampled_report_id(mut self, new_value: &str) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + self._unsampled_report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUnsampledReportGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUnsampledReportGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUnsampledReportGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new profile filter link. +/// +/// A builder for the *profileFilterLinks.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::ProfileFilterLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProfileFilterLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_insert(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: ProfileFilterLink, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProfileFilterLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProfileFilterLink) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create profile filter link for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id to create profile filter link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to create filter link for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing filter. +/// +/// A builder for the *filters.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Filter; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Filter = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_update(&req, "accountId", "filterId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Filter, + _account_id: String, + _filter_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filter)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("filterId", self._filter_id.to_string())); + for &field in ["alt", "accountId", "filterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters/{filterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{filterId}", "filterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "filterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Filter) -> ManagementFilterUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the filter belongs. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *filter id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the filter to be updated. + pub fn filter_id(mut self, new_value: &str) -> ManagementFilterUpdateCall<'a, C, NC, A> { + self._filter_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a profile filter link. +/// +/// A builder for the *profileFilterLinks.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_delete("accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the profile filter link belongs. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id to which the profile filter link belongs. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to which the filter link belongs. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the profile filter link to delete. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists segments to which the user has access. +/// +/// A builder for the *segments.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().segments_list() +/// .start_index(-82) +/// .max_results(-5) +/// .doit(); +/// # } +/// ``` +pub struct ManagementSegmentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementSegmentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementSegmentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Segments)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.segments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/segments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first segment to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementSegmentListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of segments to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementSegmentListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementSegmentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementSegmentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementSegmentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a view (profile). +/// +/// A builder for the *profiles.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_delete("accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to delete the view (profile) for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to delete the view (profile) for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the view (profile) to be deleted. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing view (profile). This method supports patch semantics. +/// +/// A builder for the *goals.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Goal; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Goal = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().goals_patch(&req, "accountId", "webPropertyId", "profileId", "goalId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementGoalPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Goal, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _goal_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementGoalPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementGoalPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Goal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.goals.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("goalId", self._goal_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "goalId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{goalId}", "goalId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "goalId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Goal) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to update the goal. + pub fn account_id(mut self, new_value: &str) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to update the goal. + pub fn web_property_id(mut self, new_value: &str) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to update the goal. + pub fn profile_id(mut self, new_value: &str) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *goal id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Index of the goal to be updated. + pub fn goal_id(mut self, new_value: &str) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._goal_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementGoalPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementGoalPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementGoalPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing custom dimension. This method supports patch semantics. +/// +/// A builder for the *customDimensions.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomDimension; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomDimension = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_dimensions_patch(&req, "accountId", "webPropertyId", "customDimensionId") +/// .ignore_custom_data_source_links(true) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDimensionPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomDimension, + _account_id: String, + _web_property_id: String, + _custom_dimension_id: String, + _ignore_custom_data_source_links: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDimensionPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDimensionPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDimension)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDimensions.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDimensionId", self._custom_dimension_id.to_string())); + if let Some(value) = self._ignore_custom_data_source_links { + params.push(("ignoreCustomDataSourceLinks", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "customDimensionId", "ignoreCustomDataSourceLinks"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDimensions/{customDimensionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDimensionId}", "customDimensionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDimensionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomDimension) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom dimension to update. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimension to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom dimension id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom dimension ID for the custom dimension to update. + pub fn custom_dimension_id(mut self, new_value: &str) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._custom_dimension_id = new_value.to_string(); + self + } + /// Sets the *ignore custom data source links* query property to the given value. + /// + /// + /// Force the update and ignore any warnings related to the custom dimension being linked to a custom data source / data set. + pub fn ignore_custom_data_source_links(mut self, new_value: bool) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._ignore_custom_data_source_links = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDimensionPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update an existing experiment. This method supports patch semantics. +/// +/// A builder for the *experiments.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Experiment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Experiment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_patch(&req, "accountId", "webPropertyId", "profileId", "experimentId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Experiment, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _experiment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Experiment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("experimentId", self._experiment_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "experimentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{experimentId}", "experimentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "experimentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Experiment) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID of the experiment to update. + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID of the experiment to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID of the experiment to update. + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *experiment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Experiment ID of the experiment to update. + pub fn experiment_id(mut self, new_value: &str) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._experiment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists experiments to which the user has access. +/// +/// A builder for the *experiments.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_list("accountId", "webPropertyId", "profileId") +/// .start_index(-53) +/// .max_results(-40) +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Experiments)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "profileId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve experiments for. + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve experiments for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve experiments for. + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first experiment to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementExperimentListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of experiments to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementExperimentListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists views (profiles) to which the user has access. +/// +/// A builder for the *profiles.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_list("accountId", "webPropertyId") +/// .start_index(-30) +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Profiles)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the view (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementProfileListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of views (profiles) to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementProfileListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists goals to which the user has access. +/// +/// A builder for the *goals.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().goals_list("accountId", "webPropertyId", "profileId") +/// .start_index(-38) +/// .max_results(-59) +/// .doit(); +/// # } +/// ``` +pub struct ManagementGoalListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementGoalListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementGoalListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Goals)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.goals.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "profileId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve goals for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to. + pub fn account_id(mut self, new_value: &str) -> ManagementGoalListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to. + pub fn web_property_id(mut self, new_value: &str) -> ManagementGoalListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve goals for. Can either be a specific view (profile) ID or '~all', which refers to all the views (profiles) that user has access to. + pub fn profile_id(mut self, new_value: &str) -> ManagementGoalListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first goal to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementGoalListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of goals to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementGoalListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementGoalListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementGoalListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementGoalListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new goal. +/// +/// A builder for the *goals.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Goal; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Goal = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().goals_insert(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementGoalInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Goal, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementGoalInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementGoalInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Goal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.goals.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Goal) -> ManagementGoalInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the goal for. + pub fn account_id(mut self, new_value: &str) -> ManagementGoalInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to create the goal for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementGoalInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to create the goal for. + pub fn profile_id(mut self, new_value: &str) -> ManagementGoalInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementGoalInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementGoalInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementGoalInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing custom metric. This method supports patch semantics. +/// +/// A builder for the *customMetrics.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomMetric; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomMetric = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_metrics_patch(&req, "accountId", "webPropertyId", "customMetricId") +/// .ignore_custom_data_source_links(true) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomMetricPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomMetric, + _account_id: String, + _web_property_id: String, + _custom_metric_id: String, + _ignore_custom_data_source_links: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomMetricPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomMetricPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customMetrics.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customMetricId", self._custom_metric_id.to_string())); + if let Some(value) = self._ignore_custom_data_source_links { + params.push(("ignoreCustomDataSourceLinks", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "customMetricId", "ignoreCustomDataSourceLinks"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customMetrics/{customMetricId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customMetricId}", "customMetricId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customMetricId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomMetric) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom metric to update. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom metric to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom metric id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom metric ID for the custom metric to update. + pub fn custom_metric_id(mut self, new_value: &str) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._custom_metric_id = new_value.to_string(); + self + } + /// Sets the *ignore custom data source links* query property to the given value. + /// + /// + /// Force the update and ignore any warnings related to the custom metric being linked to a custom data source / data set. + pub fn ignore_custom_data_source_links(mut self, new_value: bool) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._ignore_custom_data_source_links = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomMetricPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomMetricPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomMetricPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Upload data for a custom data source. +/// +/// A builder for the *uploads.uploadData* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().uploads_upload_data("accountId", "webPropertyId", "customDataSourceId") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct ManagementUploadUploadDataCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _custom_data_source_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUploadUploadDataCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUploadUploadDataCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, Upload)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.uploads.uploadData", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDataSourceId", self._custom_data_source_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "customDataSourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDataSourceId}", "customDataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + if protocol == "simple" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + req = req.header(ContentType(reader_mime_type.clone())) + .header(ContentLength(size)) + .body(&mut reader); + } + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 1GB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Upload)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 1GB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Upload)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account Id associated with the upload. + pub fn account_id(mut self, new_value: &str) -> ManagementUploadUploadDataCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property UA-string associated with the upload. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUploadUploadDataCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom data source Id to which the data being uploaded belongs. + pub fn custom_data_source_id(mut self, new_value: &str) -> ManagementUploadUploadDataCall<'a, C, NC, A> { + self._custom_data_source_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUploadUploadDataCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUploadUploadDataCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUploadUploadDataCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a new user to the given account. +/// +/// A builder for the *accountUserLinks.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().account_user_links_insert(&req, "accountId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountUserLinkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountUserLinkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountUserLinkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accountUserLinks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a new user to the given web property. +/// +/// A builder for the *webpropertyUserLinks.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperty_user_links_insert(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webpropertyUserLinks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID to create the user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete an experiment. +/// +/// A builder for the *experiments.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_delete("accountId", "webPropertyId", "profileId", "experimentId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _experiment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("experimentId", self._experiment_id.to_string())); + for &field in ["accountId", "webPropertyId", "profileId", "experimentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{experimentId}", "experimentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "experimentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the experiment belongs + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to which the experiment belongs + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to which the experiment belongs + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *experiment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the experiment to delete + pub fn experiment_id(mut self, new_value: &str) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + self._experiment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing view (profile). This method supports patch semantics. +/// +/// A builder for the *profiles.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Profile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Profile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_patch(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfilePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Profile, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfilePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfilePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Profile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Profile) -> ManagementProfilePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the view (profile) belongs + pub fn account_id(mut self, new_value: &str) -> ManagementProfilePatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to which the view (profile) belongs + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfilePatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the view (profile) to be updated. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfilePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfilePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfilePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfilePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a filters to which the user has access. +/// +/// A builder for the *filters.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_get("accountId", "filterId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _filter_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filter)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("filterId", self._filter_id.to_string())); + for &field in ["alt", "accountId", "filterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters/{filterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{filterId}", "filterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "filterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve filters for. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *filter id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Filter ID to retrieve filters for. + pub fn filter_id(mut self, new_value: &str) -> ManagementFilterGetCall<'a, C, NC, A> { + self._filter_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists webProperty-AdWords links for a given web property. +/// +/// A builder for the *webPropertyAdWordsLinks.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_list("accountId", "webPropertyId") +/// .start_index(-67) +/// .max_results(-17) +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityAdWordsLinks)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the account which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the AdWords links for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first webProperty-AdWords link to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of webProperty-AdWords links to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists account summaries (lightweight tree comprised of accounts/properties/profiles) to which the user has access. +/// +/// A builder for the *accountSummaries.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().account_summaries_list() +/// .start_index(-74) +/// .max_results(-48) +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountSummaryListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountSummaryListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountSummaryListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountSummaries)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accountSummaries.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accountSummaries".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementAccountSummaryListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of account summaries to include in this response, where the largest acceptable value is 1000. + pub fn max_results(mut self, new_value: i32) -> ManagementAccountSummaryListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountSummaryListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountSummaryListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountSummaryListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists custom dimensions to which the user has access. +/// +/// A builder for the *customDimensions.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_dimensions_list("accountId", "webPropertyId") +/// .start_index(-87) +/// .max_results(-15) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDimensionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDimensionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDimensionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDimensions)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDimensions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDimensions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom dimensions to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimensions to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of custom dimensions to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDimensionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDimensionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDimensionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List uploads to which the user has access. +/// +/// A builder for the *uploads.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().uploads_list("accountId", "webPropertyId", "customDataSourceId") +/// .start_index(-90) +/// .max_results(-77) +/// .doit(); +/// # } +/// ``` +pub struct ManagementUploadListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _custom_data_source_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUploadListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUploadListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Uploads)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.uploads.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDataSourceId", self._custom_data_source_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "customDataSourceId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/uploads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDataSourceId}", "customDataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account Id for the uploads to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementUploadListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id for the uploads to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUploadListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom data source Id for uploads to retrieve. + pub fn custom_data_source_id(mut self, new_value: &str) -> ManagementUploadListCall<'a, C, NC, A> { + self._custom_data_source_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// A 1-based index of the first upload to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementUploadListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of uploads to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementUploadListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUploadListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUploadListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUploadListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists profile-user links for a given view (profile). +/// +/// A builder for the *profileUserLinks.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_user_links_list("accountId", "webPropertyId", "profileId") +/// .start_index(-47) +/// .max_results(-8) +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileUserLinkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileUserLinkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileUserLinkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLinks)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileUserLinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "profileId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID which the given view (profile) belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID which the given view (profile) belongs to. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve the profile-user links for. Can either be a specific profile ID or '~all', which refers to all the profiles that user has access to. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first profile-user link to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of profile-user links to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileUserLinkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileUserLinkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileUserLinkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists account-user links for a given account. +/// +/// A builder for the *accountUserLinks.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().account_user_links_list("accountId") +/// .start_index(-91) +/// .max_results(-15) +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountUserLinkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountUserLinkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountUserLinkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLinks)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accountUserLinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve the user links for. + pub fn account_id(mut self, new_value: &str) -> ManagementAccountUserLinkListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first account-user link to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementAccountUserLinkListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of account-user links to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementAccountUserLinkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountUserLinkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountUserLinkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountUserLinkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing custom metric. +/// +/// A builder for the *customMetrics.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomMetric; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomMetric = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_metrics_update(&req, "accountId", "webPropertyId", "customMetricId") +/// .ignore_custom_data_source_links(true) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomMetricUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomMetric, + _account_id: String, + _web_property_id: String, + _custom_metric_id: String, + _ignore_custom_data_source_links: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomMetricUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomMetricUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customMetrics.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customMetricId", self._custom_metric_id.to_string())); + if let Some(value) = self._ignore_custom_data_source_links { + params.push(("ignoreCustomDataSourceLinks", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "customMetricId", "ignoreCustomDataSourceLinks"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customMetrics/{customMetricId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customMetricId}", "customMetricId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customMetricId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomMetric) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom metric to update. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom metric to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom metric id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom metric ID for the custom metric to update. + pub fn custom_metric_id(mut self, new_value: &str) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._custom_metric_id = new_value.to_string(); + self + } + /// Sets the *ignore custom data source links* query property to the given value. + /// + /// + /// Force the update and ignore any warnings related to the custom metric being linked to a custom data source / data set. + pub fn ignore_custom_data_source_links(mut self, new_value: bool) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._ignore_custom_data_source_links = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomMetricUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete data associated with a previous upload. +/// +/// A builder for the *uploads.deleteUploadData* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::AnalyticsDataimportDeleteUploadDataRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AnalyticsDataimportDeleteUploadDataRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().uploads_delete_upload_data(&req, "accountId", "webPropertyId", "customDataSourceId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementUploadDeleteUploadDataCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: AnalyticsDataimportDeleteUploadDataRequest, + _account_id: String, + _web_property_id: String, + _custom_data_source_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUploadDeleteUploadDataCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.uploads.deleteUploadData", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDataSourceId", self._custom_data_source_id.to_string())); + for &field in ["accountId", "webPropertyId", "customDataSourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources/{customDataSourceId}/deleteUploadData".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDataSourceId}", "customDataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AnalyticsDataimportDeleteUploadDataRequest) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account Id for the uploads to be deleted. + pub fn account_id(mut self, new_value: &str) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id for the uploads to be deleted. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Custom data source Id for the uploads to be deleted. + pub fn custom_data_source_id(mut self, new_value: &str) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + self._custom_data_source_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUploadDeleteUploadDataCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update an existing experiment. +/// +/// A builder for the *experiments.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Experiment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Experiment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_update(&req, "accountId", "webPropertyId", "profileId", "experimentId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Experiment, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _experiment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Experiment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("experimentId", self._experiment_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "experimentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments/{experimentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{experimentId}", "experimentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "experimentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Experiment) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID of the experiment to update. + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID of the experiment to update. + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID of the experiment to update. + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *experiment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Experiment ID of the experiment to update. + pub fn experiment_id(mut self, new_value: &str) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._experiment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing view (profile). +/// +/// A builder for the *goals.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Goal; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Goal = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().goals_update(&req, "accountId", "webPropertyId", "profileId", "goalId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementGoalUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Goal, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _goal_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementGoalUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementGoalUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Goal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.goals.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("goalId", self._goal_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "goalId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{goalId}", "goalId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "goalId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Goal) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to update the goal. + pub fn account_id(mut self, new_value: &str) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to update the goal. + pub fn web_property_id(mut self, new_value: &str) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to update the goal. + pub fn profile_id(mut self, new_value: &str) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *goal id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Index of the goal to be updated. + pub fn goal_id(mut self, new_value: &str) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._goal_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementGoalUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementGoalUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementGoalUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List custom data sources to which the user has access. +/// +/// A builder for the *customDataSources.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_data_sources_list("accountId", "webPropertyId") +/// .start_index(-26) +/// .max_results(-36) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDataSourceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDataSourceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDataSourceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDataSources)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDataSources.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDataSources".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account Id for the custom data sources to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id for the custom data sources to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// A 1-based index of the first custom data source to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of custom data sources to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDataSourceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDataSourceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDataSourceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists custom metrics to which the user has access. +/// +/// A builder for the *customMetrics.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_metrics_list("accountId", "webPropertyId") +/// .start_index(-55) +/// .max_results(-20) +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomMetricListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomMetricListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomMetricListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomMetrics)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customMetrics.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customMetrics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom metrics to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomMetricListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom metrics to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomMetricListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementCustomMetricListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of custom metrics to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementCustomMetricListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomMetricListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomMetricListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomMetricListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists unsampled reports to which the user has access. +/// +/// A builder for the *unsampledReports.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().unsampled_reports_list("accountId", "webPropertyId", "profileId") +/// .start_index(-58) +/// .max_results(-21) +/// .doit(); +/// # } +/// ``` +pub struct ManagementUnsampledReportListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementUnsampledReportListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementUnsampledReportListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UnsampledReports)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.unsampledReports.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "profileId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/unsampledReports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve unsampled reports for. Must be a specific account ID, ~all is not supported. + pub fn account_id(mut self, new_value: &str) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve unsampled reports for. Must be a specific web property ID, ~all is not supported. + pub fn web_property_id(mut self, new_value: &str) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve unsampled reports for. Must be a specific view (profile) ID, ~all is not supported. + pub fn profile_id(mut self, new_value: &str) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first unsampled report to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of unsampled reports to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementUnsampledReportListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementUnsampledReportListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementUnsampledReportListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a web property to which the user has access. +/// +/// A builder for the *webproperties.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperties_get("accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Webproperty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webproperties.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve the web property for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID to retrieve the web property for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new experiment. +/// +/// A builder for the *experiments.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Experiment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Experiment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().experiments_insert(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementExperimentInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Experiment, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementExperimentInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementExperimentInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Experiment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.experiments.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Experiment) -> ManagementExperimentInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the experiment for. + pub fn account_id(mut self, new_value: &str) -> ManagementExperimentInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to create the experiment for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementExperimentInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to create the experiment for. + pub fn profile_id(mut self, new_value: &str) -> ManagementExperimentInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementExperimentInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementExperimentInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementExperimentInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get a custom dimension to which the user has access. +/// +/// A builder for the *customDimensions.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_dimensions_get("accountId", "webPropertyId", "customDimensionId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDimensionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _custom_dimension_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDimensionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDimensionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDimension)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDimensions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("customDimensionId", self._custom_dimension_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "customDimensionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDimensions/{customDimensionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{customDimensionId}", "customDimensionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "customDimensionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom dimension to retrieve. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDimensionGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimension to retrieve. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDimensionGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *custom dimension id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the custom dimension to retrieve. + pub fn custom_dimension_id(mut self, new_value: &str) -> ManagementCustomDimensionGetCall<'a, C, NC, A> { + self._custom_dimension_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDimensionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDimensionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDimensionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all profile filter links for a profile. +/// +/// A builder for the *profileFilterLinks.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_list("accountId", "webPropertyId", "profileId") +/// .start_index(-43) +/// .max_results(-77) +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProfileFilterLinks)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "webPropertyId", "profileId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve profile filter links for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id for profile filter links for. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to retrieve filter links for. Can either be a specific profile ID or '~all', which refers to all the profiles that user has access to. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of profile filter links to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing web property. This method supports patch semantics. +/// +/// A builder for the *webproperties.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Webproperty; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Webproperty = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperties_patch(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Webproperty, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Webproperty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webproperties.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Webproperty) -> ManagementWebpropertyPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the web property belongs + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebpropertyPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new custom dimension. +/// +/// A builder for the *customDimensions.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomDimension; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomDimension = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_dimensions_insert(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomDimensionInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomDimension, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomDimensionInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomDimensionInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomDimension)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customDimensions.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customDimensions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomDimension) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom dimension to create. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimension to create. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomDimensionInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new custom metric. +/// +/// A builder for the *customMetrics.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::CustomMetric; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CustomMetric = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().custom_metrics_insert(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementCustomMetricInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: CustomMetric, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementCustomMetricInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementCustomMetricInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.customMetrics.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/customMetrics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CustomMetric) -> ManagementCustomMetricInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID for the custom metric to create. + pub fn account_id(mut self, new_value: &str) -> ManagementCustomMetricInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID for the custom dimension to create. + pub fn web_property_id(mut self, new_value: &str) -> ManagementCustomMetricInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementCustomMetricInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementCustomMetricInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementCustomMetricInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a new user to the given view (profile). +/// +/// A builder for the *profileUserLinks.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityUserLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityUserLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_user_links_insert(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileUserLinkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityUserLink, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileUserLinkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileUserLinkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityUserLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileUserLinks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/entityUserLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityUserLink) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web Property ID to create the user link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to create the user link for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileUserLinkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists web properties to which the user has access. +/// +/// A builder for the *webproperties.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().webproperties_list("accountId") +/// .start_index(-35) +/// .max_results(-65) +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebpropertyListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebpropertyListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebpropertyListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Webproperties)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webproperties.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve web properties for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebpropertyListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementWebpropertyListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of web properties to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementWebpropertyListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebpropertyListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebpropertyListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebpropertyListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a webProperty-AdWords link. +/// +/// A builder for the *webPropertyAdWordsLinks.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityAdWordsLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityAdWordsLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_insert(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityAdWordsLink, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityAdWordsLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityAdWordsLink) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the Google Analytics account to create the link for. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to create the link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing webProperty-AdWords link. This method supports patch semantics. +/// +/// A builder for the *webPropertyAdWordsLinks.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityAdWordsLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityAdWordsLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_patch(&req, "accountId", "webPropertyId", "webPropertyAdWordsLinkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityAdWordsLink, + _account_id: String, + _web_property_id: String, + _web_property_ad_words_link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityAdWordsLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("webPropertyAdWordsLinkId", self._web_property_ad_words_link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks/{webPropertyAdWordsLinkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{webPropertyAdWordsLinkId}", "webPropertyAdWordsLinkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityAdWordsLink) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the account which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the AdWords link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *web property ad words link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property-AdWords link ID. + pub fn web_property_ad_words_link_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + self._web_property_ad_words_link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a goal to which the user has access. +/// +/// A builder for the *goals.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().goals_get("accountId", "webPropertyId", "profileId", "goalId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementGoalGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _goal_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementGoalGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementGoalGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Goal)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.goals.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("goalId", self._goal_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "goalId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals/{goalId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{goalId}", "goalId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "goalId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve the goal for. + pub fn account_id(mut self, new_value: &str) -> ManagementGoalGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the goal for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementGoalGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// View (Profile) ID to retrieve the goal for. + pub fn profile_id(mut self, new_value: &str) -> ManagementGoalGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *goal id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Goal ID to retrieve the goal for. + pub fn goal_id(mut self, new_value: &str) -> ManagementGoalGetCall<'a, C, NC, A> { + self._goal_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementGoalGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementGoalGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementGoalGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a web property-AdWords link. +/// +/// A builder for the *webPropertyAdWordsLinks.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_delete("accountId", "webPropertyId", "webPropertyAdWordsLinkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _web_property_ad_words_link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("webPropertyAdWordsLinkId", self._web_property_ad_words_link_id.to_string())); + for &field in ["accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks/{webPropertyAdWordsLinkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{webPropertyAdWordsLinkId}", "webPropertyAdWordsLinkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the account which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to delete the AdWords link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *web property ad words link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property AdWords link ID. + pub fn web_property_ad_words_link_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> { + self._web_property_ad_words_link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing webProperty-AdWords link. +/// +/// A builder for the *webPropertyAdWordsLinks.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::EntityAdWordsLink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EntityAdWordsLink = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().web_property_ad_words_links_update(&req, "accountId", "webPropertyId", "webPropertyAdWordsLinkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: EntityAdWordsLink, + _account_id: String, + _web_property_id: String, + _web_property_ad_words_link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntityAdWordsLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.webPropertyAdWordsLinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("webPropertyAdWordsLinkId", self._web_property_ad_words_link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/entityAdWordsLinks/{webPropertyAdWordsLinkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{webPropertyAdWordsLinkId}", "webPropertyAdWordsLinkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "webPropertyAdWordsLinkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EntityAdWordsLink) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the account which the given web property belongs to. + pub fn account_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to retrieve the AdWords link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *web property ad words link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property-AdWords link ID. + pub fn web_property_ad_words_link_id(mut self, new_value: &str) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + self._web_property_ad_words_link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementWebPropertyAdWordsLinkUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing filter. This method supports patch semantics. +/// +/// A builder for the *filters.patch* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Filter; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Filter = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_patch(&req, "accountId", "filterId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Filter, + _account_id: String, + _filter_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filter)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("filterId", self._filter_id.to_string())); + for &field in ["alt", "accountId", "filterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters/{filterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{filterId}", "filterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "filterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Filter) -> ManagementFilterPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the filter belongs. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *filter id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the filter to be updated. + pub fn filter_id(mut self, new_value: &str) -> ManagementFilterPatchCall<'a, C, NC, A> { + self._filter_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all filters for an account +/// +/// A builder for the *filters.list* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_list("accountId") +/// .start_index(-24) +/// .max_results(-69) +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filters)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + for &field in ["alt", "accountId", "start-index", "max-results"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve filters for. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterListCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> ManagementFilterListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of filters to include in this response. + pub fn max_results(mut self, new_value: i32) -> ManagementFilterListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a filter. +/// +/// A builder for the *filters.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().filters_delete("accountId", "filterId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementFilterDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _filter_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementFilterDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementFilterDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Filter)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.filters.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("filterId", self._filter_id.to_string())); + for &field in ["alt", "accountId", "filterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/filters/{filterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{filterId}", "filterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "filterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to delete the filter for. + pub fn account_id(mut self, new_value: &str) -> ManagementFilterDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *filter id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the filter to be deleted. + pub fn filter_id(mut self, new_value: &str) -> ManagementFilterDeleteCall<'a, C, NC, A> { + self._filter_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementFilterDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementFilterDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementFilterDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new view (profile). +/// +/// A builder for the *profiles.insert* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Profile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Profile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_insert(&req, "accountId", "webPropertyId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Profile, + _account_id: String, + _web_property_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Profile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "webPropertyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Profile) -> ManagementProfileInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to create the view (profile) for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileInsertCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to create the view (profile) for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileInsertCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a user from the given account. +/// +/// A builder for the *accountUserLinks.delete* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().account_user_links_delete("accountId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementAccountUserLinkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementAccountUserLinkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.accountUserLinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["accountId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/entityUserLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["accountId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to delete the user link for. + pub fn account_id(mut self, new_value: &str) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Link ID to delete the user link for. + pub fn link_id(mut self, new_value: &str) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementAccountUserLinkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing view (profile). +/// +/// A builder for the *profiles.update* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::Profile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Profile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profiles_update(&req, "accountId", "webPropertyId", "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: Profile, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Profile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profiles.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["accountId", "webPropertyId", "profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Profile) -> ManagementProfileUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to which the view (profile) belongs + pub fn account_id(mut self, new_value: &str) -> ManagementProfileUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property ID to which the view (profile) belongs + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileUpdateCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the view (profile) to be updated. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a single profile filter link. +/// +/// A builder for the *profileFilterLinks.get* method supported by a *management* resource. +/// It is not used directly, but through a `ManagementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.management().profile_filter_links_get("accountId", "webPropertyId", "profileId", "linkId") +/// .doit(); +/// # } +/// ``` +pub struct ManagementProfileFilterLinkGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _account_id: String, + _web_property_id: String, + _profile_id: String, + _link_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagementProfileFilterLinkGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagementProfileFilterLinkGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProfileFilterLink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.management.profileFilterLinks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + params.push(("webPropertyId", self._web_property_id.to_string())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("linkId", self._link_id.to_string())); + for &field in ["alt", "accountId", "webPropertyId", "profileId", "linkId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/profileFilterLinks/{linkId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{webPropertyId}", "webPropertyId"), ("{profileId}", "profileId"), ("{linkId}", "linkId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["accountId", "webPropertyId", "profileId", "linkId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID to retrieve profile filter link for. + pub fn account_id(mut self, new_value: &str) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *web property id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Web property Id to retrieve profile filter link for. + pub fn web_property_id(mut self, new_value: &str) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + self._web_property_id = new_value.to_string(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Profile ID to retrieve filter link for. + pub fn profile_id(mut self, new_value: &str) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *link id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the profile filter link. + pub fn link_id(mut self, new_value: &str) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + self._link_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagementProfileFilterLinkGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns Analytics Multi-Channel Funnels data for a view (profile). +/// +/// A builder for the *mcf.get* method supported by a *data* resource. +/// It is not used directly, but through a `DataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.data().mcf_get("ids", "start-date", "end-date", "metrics") +/// .start_index(-86) +/// .sort("diam") +/// .sampling_level("nonumy") +/// .max_results(-93) +/// .filters("diam") +/// .dimensions("magna") +/// .doit(); +/// # } +/// ``` +pub struct DataMcfGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _ids: String, + _start_date: String, + _end_date: String, + _metrics: String, + _start_index: Option, + _sort: Option, + _sampling_level: Option, + _max_results: Option, + _filters: Option, + _dimensions: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DataMcfGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DataMcfGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, McfData)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.data.mcf.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("ids", self._ids.to_string())); + params.push(("start-date", self._start_date.to_string())); + params.push(("end-date", self._end_date.to_string())); + params.push(("metrics", self._metrics.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._sort { + params.push(("sort", value.to_string())); + } + if let Some(value) = self._sampling_level { + params.push(("samplingLevel", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._dimensions { + params.push(("dimensions", value.to_string())); + } + for &field in ["alt", "ids", "start-date", "end-date", "metrics", "start-index", "sort", "samplingLevel", "max-results", "filters", "dimensions"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/data/mcf".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ids* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID. + pub fn ids(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._ids = new_value.to_string(); + self + } + /// Sets the *start-date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is 7daysAgo. + pub fn start_date(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end-date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is 7daysAgo. + pub fn end_date(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *metrics* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified. + pub fn metrics(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._metrics = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> DataMcfGetCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *sort* query property to the given value. + /// + /// + /// A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data. + pub fn sort(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._sort = Some(new_value.to_string()); + self + } + /// Sets the *sampling level* query property to the given value. + /// + /// + /// The desired sampling level. + pub fn sampling_level(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._sampling_level = Some(new_value.to_string()); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of entries to include in this feed. + pub fn max_results(mut self, new_value: i32) -> DataMcfGetCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// A comma-separated list of dimension or metric filters to be applied to the Analytics data. + pub fn filters(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *dimensions* query property to the given value. + /// + /// + /// A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'. + pub fn dimensions(mut self, new_value: &str) -> DataMcfGetCall<'a, C, NC, A> { + self._dimensions = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DataMcfGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DataMcfGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DataMcfGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns Analytics data for a view (profile). +/// +/// A builder for the *ga.get* method supported by a *data* resource. +/// It is not used directly, but through a `DataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.data().ga_get("ids", "start-date", "end-date", "metrics") +/// .start_index(-91) +/// .sort("takimata") +/// .segment("dolores") +/// .sampling_level("consetetur") +/// .output("erat") +/// .max_results(-52) +/// .filters("dolores") +/// .dimensions("dolores") +/// .doit(); +/// # } +/// ``` +pub struct DataGaGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _ids: String, + _start_date: String, + _end_date: String, + _metrics: String, + _start_index: Option, + _sort: Option, + _segment: Option, + _sampling_level: Option, + _output: Option, + _max_results: Option, + _filters: Option, + _dimensions: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DataGaGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DataGaGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GaData)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.data.ga.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((14 + self._additional_params.len())); + params.push(("ids", self._ids.to_string())); + params.push(("start-date", self._start_date.to_string())); + params.push(("end-date", self._end_date.to_string())); + params.push(("metrics", self._metrics.to_string())); + if let Some(value) = self._start_index { + params.push(("start-index", value.to_string())); + } + if let Some(value) = self._sort { + params.push(("sort", value.to_string())); + } + if let Some(value) = self._segment { + params.push(("segment", value.to_string())); + } + if let Some(value) = self._sampling_level { + params.push(("samplingLevel", value.to_string())); + } + if let Some(value) = self._output { + params.push(("output", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._dimensions { + params.push(("dimensions", value.to_string())); + } + for &field in ["alt", "ids", "start-date", "end-date", "metrics", "start-index", "sort", "segment", "samplingLevel", "output", "max-results", "filters", "dimensions"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/data/ga".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ids* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID. + pub fn ids(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._ids = new_value.to_string(); + self + } + /// Sets the *start-date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start date for fetching Analytics data. Requests can specify a start date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is 7daysAgo. + pub fn start_date(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._start_date = new_value.to_string(); + self + } + /// Sets the *end-date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End date for fetching Analytics data. Request can should specify an end date formatted as YYYY-MM-DD, or as a relative date (e.g., today, yesterday, or 7daysAgo). The default value is yesterday. + pub fn end_date(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._end_date = new_value.to_string(); + self + } + /// Sets the *metrics* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// A comma-separated list of Analytics metrics. E.g., 'ga:sessions,ga:pageviews'. At least one metric must be specified. + pub fn metrics(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._metrics = new_value.to_string(); + self + } + /// Sets the *start-index* query property to the given value. + /// + /// + /// An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. + pub fn start_index(mut self, new_value: i32) -> DataGaGetCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *sort* query property to the given value. + /// + /// + /// A comma-separated list of dimensions or metrics that determine the sort order for Analytics data. + pub fn sort(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._sort = Some(new_value.to_string()); + self + } + /// Sets the *segment* query property to the given value. + /// + /// + /// An Analytics segment to be applied to data. + pub fn segment(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._segment = Some(new_value.to_string()); + self + } + /// Sets the *sampling level* query property to the given value. + /// + /// + /// The desired sampling level. + pub fn sampling_level(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._sampling_level = Some(new_value.to_string()); + self + } + /// Sets the *output* query property to the given value. + /// + /// + /// The selected format for the response. Default format is JSON. + pub fn output(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._output = Some(new_value.to_string()); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of entries to include in this feed. + pub fn max_results(mut self, new_value: i32) -> DataGaGetCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// A comma-separated list of dimension or metric filters to be applied to Analytics data. + pub fn filters(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *dimensions* query property to the given value. + /// + /// + /// A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'. + pub fn dimensions(mut self, new_value: &str) -> DataGaGetCall<'a, C, NC, A> { + self._dimensions = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DataGaGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DataGaGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DataGaGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns real time data for a view (profile). +/// +/// A builder for the *realtime.get* method supported by a *data* resource. +/// It is not used directly, but through a `DataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.data().realtime_get("ids", "metrics") +/// .sort("et") +/// .max_results(-31) +/// .filters("nonumy") +/// .dimensions("sit") +/// .doit(); +/// # } +/// ``` +pub struct DataRealtimeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _ids: String, + _metrics: String, + _sort: Option, + _max_results: Option, + _filters: Option, + _dimensions: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DataRealtimeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DataRealtimeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RealtimeData)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.data.realtime.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("ids", self._ids.to_string())); + params.push(("metrics", self._metrics.to_string())); + if let Some(value) = self._sort { + params.push(("sort", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("max-results", value.to_string())); + } + if let Some(value) = self._filters { + params.push(("filters", value.to_string())); + } + if let Some(value) = self._dimensions { + params.push(("dimensions", value.to_string())); + } + for &field in ["alt", "ids", "metrics", "sort", "max-results", "filters", "dimensions"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/data/realtime".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *ids* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique table ID for retrieving real time data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID. + pub fn ids(mut self, new_value: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + self._ids = new_value.to_string(); + self + } + /// Sets the *metrics* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// A comma-separated list of real time metrics. E.g., 'rt:activeUsers'. At least one metric must be specified. + pub fn metrics(mut self, new_value: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + self._metrics = new_value.to_string(); + self + } + /// Sets the *sort* query property to the given value. + /// + /// + /// A comma-separated list of dimensions or metrics that determine the sort order for real time data. + pub fn sort(mut self, new_value: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + self._sort = Some(new_value.to_string()); + self + } + /// Sets the *max-results* query property to the given value. + /// + /// + /// The maximum number of entries to include in this feed. + pub fn max_results(mut self, new_value: i32) -> DataRealtimeGetCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filters* query property to the given value. + /// + /// + /// A comma-separated list of dimension or metric filters to be applied to real time data. + pub fn filters(mut self, new_value: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + self._filters = Some(new_value.to_string()); + self + } + /// Sets the *dimensions* query property to the given value. + /// + /// + /// A comma-separated list of real time dimensions. E.g., 'rt:medium,rt:city'. + pub fn dimensions(mut self, new_value: &str) -> DataRealtimeGetCall<'a, C, NC, A> { + self._dimensions = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DataRealtimeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DataRealtimeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DataRealtimeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an account ticket. +/// +/// A builder for the *createAccountTicket* method supported by a *provisioning* resource. +/// It is not used directly, but through a `ProvisioningMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// use analytics3::AccountTicket; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountTicket = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.provisioning().create_account_ticket(&req) +/// .doit(); +/// # } +/// ``` +pub struct ProvisioningCreateAccountTicketCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _request: AccountTicket, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProvisioningCreateAccountTicketCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProvisioningCreateAccountTicketCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountTicket)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.provisioning.createAccountTicket", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/provisioning/createAccountTicket".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountTicket) -> ProvisioningCreateAccountTicketCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProvisioningCreateAccountTicketCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProvisioningCreateAccountTicketCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProvisioningCreateAccountTicketCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all columns for a report type +/// +/// A builder for the *columns.list* method supported by a *metadata* resource. +/// It is not used directly, but through a `MetadataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-analytics3" as analytics3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use analytics3::Analytics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Analytics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metadata().columns_list("reportType") +/// .doit(); +/// # } +/// ``` +pub struct MetadataColumnListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Analytics, + _report_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetadataColumnListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetadataColumnListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Columns)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "analytics.metadata.columns.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("reportType", self._report_type.to_string())); + for &field in ["alt", "reportType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/analytics/v3/metadata/{reportType}/columns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ManageUserReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{reportType}", "reportType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["reportType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *report type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Report type. Allowed Values: 'ga'. Where 'ga' corresponds to the Core Reporting API + pub fn report_type(mut self, new_value: &str) -> MetadataColumnListCall<'a, C, NC, A> { + self._report_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetadataColumnListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetadataColumnListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetadataColumnListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/androidenterprise1/Cargo.toml b/gen/androidenterprise1/Cargo.toml new file mode 100644 index 0000000000..732eed4e79 --- /dev/null +++ b/gen/androidenterprise1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-androidenterprise1" +version = "0.1.0+20150218" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Android Enterprise (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/androidenterprise1" +homepage = "https://developers.google.com/play/enterprise" +documentation = "http://byron.github.io/google-apis-rs/google-androidenterprise1" +license = "MIT" +keywords = ["androidenterprise", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/androidenterprise1/LICENSE.md b/gen/androidenterprise1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/androidenterprise1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/androidenterprise1/README.md b/gen/androidenterprise1/README.md new file mode 100644 index 0000000000..48986dea42 --- /dev/null +++ b/gen/androidenterprise1/README.md @@ -0,0 +1,195 @@ + +The `google-androidenterprise1` library allows access to all features of the *Google Android Enterprise* service. + +This documentation was generated from *Android Enterprise* crate version *0.1.0+20150218*, where *20150218* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Android Enterprise* *v1* API can be found at the +[official documentation site](https://developers.google.com/play/enterprise). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.AndroidEnterprise.html) ... + +* [collections](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Collection.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionUpdateCall.html) +* collectionviewers + * [*delete*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionviewerDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionviewerGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionviewerListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionviewerPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.CollectionviewerUpdateCall.html) +* [devices](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Device.html) + * [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.DeviceGetCall.html), [*get state*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.DeviceGetStateCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.DeviceListCall.html) and [*set state*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.DeviceSetStateCall.html) +* [enterprises](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Enterprise.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseDeleteCall.html), [*enroll*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseEnrollCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseListCall.html), [*set account*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseSetAccountCall.html) and [*unenroll*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EnterpriseUnenrollCall.html) +* [entitlements](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Entitlement.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EntitlementDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EntitlementGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EntitlementListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EntitlementPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.EntitlementUpdateCall.html) +* grouplicenses + * [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.GrouplicenseGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.GrouplicenseListCall.html) +* grouplicenseusers + * [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.GrouplicenseuserListCall.html) +* [installs](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Install.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.InstallDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.InstallGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.InstallListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.InstallPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.InstallUpdateCall.html) +* [permissions](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Permission.html) + * [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.PermissionGetCall.html) +* [products](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.Product.html) + * [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.ProductGetCall.html), [*get app restrictions schema*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.ProductGetAppRestrictionsSchemaCall.html), [*get permissions*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.ProductGetPermissionCall.html) and [*update permissions*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.ProductUpdatePermissionCall.html) +* [users](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.User.html) + * [*generate token*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.UserGenerateTokenCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.UserGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.UserListCall.html) and [*revoke token*](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.UserRevokeTokenCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-androidenterprise1/struct.AndroidEnterprise.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.enterprises().insert(...).doit() +let r = hub.enterprises().list(...).doit() +let r = hub.enterprises().unenroll(...).doit() +let r = hub.enterprises().set_account(...).doit() +let r = hub.enterprises().enroll(...).doit() +let r = hub.enterprises().delete(...).doit() +let r = hub.enterprises().get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-androidenterprise1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-androidenterprise1" as androidenterprise1; +use androidenterprise1::Enterprise; +use androidenterprise1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use androidenterprise1::AndroidEnterprise; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Enterprise = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.enterprises().insert(&req, "token") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-androidenterprise1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-androidenterprise1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-androidenterprise1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-androidenterprise1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **androidenterprise1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/androidenterprise1/src/cmn.rs b/gen/androidenterprise1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/androidenterprise1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/androidenterprise1/src/lib.rs b/gen/androidenterprise1/src/lib.rs new file mode 100644 index 0000000000..fd8a451435 --- /dev/null +++ b/gen/androidenterprise1/src/lib.rs @@ -0,0 +1,13274 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Android Enterprise* crate version *0.1.0+20150218*, where *20150218* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Android Enterprise* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/play/enterprise). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/androidenterprise1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AndroidEnterprise.html) ... +//! +//! * [collections](struct.Collection.html) +//! * [*delete*](struct.CollectionDeleteCall.html), [*get*](struct.CollectionGetCall.html), [*insert*](struct.CollectionInsertCall.html), [*list*](struct.CollectionListCall.html), [*patch*](struct.CollectionPatchCall.html) and [*update*](struct.CollectionUpdateCall.html) +//! * collectionviewers +//! * [*delete*](struct.CollectionviewerDeleteCall.html), [*get*](struct.CollectionviewerGetCall.html), [*list*](struct.CollectionviewerListCall.html), [*patch*](struct.CollectionviewerPatchCall.html) and [*update*](struct.CollectionviewerUpdateCall.html) +//! * [devices](struct.Device.html) +//! * [*get*](struct.DeviceGetCall.html), [*get state*](struct.DeviceGetStateCall.html), [*list*](struct.DeviceListCall.html) and [*set state*](struct.DeviceSetStateCall.html) +//! * [enterprises](struct.Enterprise.html) +//! * [*delete*](struct.EnterpriseDeleteCall.html), [*enroll*](struct.EnterpriseEnrollCall.html), [*get*](struct.EnterpriseGetCall.html), [*insert*](struct.EnterpriseInsertCall.html), [*list*](struct.EnterpriseListCall.html), [*set account*](struct.EnterpriseSetAccountCall.html) and [*unenroll*](struct.EnterpriseUnenrollCall.html) +//! * [entitlements](struct.Entitlement.html) +//! * [*delete*](struct.EntitlementDeleteCall.html), [*get*](struct.EntitlementGetCall.html), [*list*](struct.EntitlementListCall.html), [*patch*](struct.EntitlementPatchCall.html) and [*update*](struct.EntitlementUpdateCall.html) +//! * grouplicenses +//! * [*get*](struct.GrouplicenseGetCall.html) and [*list*](struct.GrouplicenseListCall.html) +//! * grouplicenseusers +//! * [*list*](struct.GrouplicenseuserListCall.html) +//! * [installs](struct.Install.html) +//! * [*delete*](struct.InstallDeleteCall.html), [*get*](struct.InstallGetCall.html), [*list*](struct.InstallListCall.html), [*patch*](struct.InstallPatchCall.html) and [*update*](struct.InstallUpdateCall.html) +//! * [permissions](struct.Permission.html) +//! * [*get*](struct.PermissionGetCall.html) +//! * [products](struct.Product.html) +//! * [*get*](struct.ProductGetCall.html), [*get app restrictions schema*](struct.ProductGetAppRestrictionsSchemaCall.html), [*get permissions*](struct.ProductGetPermissionCall.html) and [*update permissions*](struct.ProductUpdatePermissionCall.html) +//! * [users](struct.User.html) +//! * [*generate token*](struct.UserGenerateTokenCall.html), [*get*](struct.UserGetCall.html), [*list*](struct.UserListCall.html) and [*revoke token*](struct.UserRevokeTokenCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AndroidEnterprise.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.enterprises().insert(...).doit() +//! let r = hub.enterprises().list(...).doit() +//! let r = hub.enterprises().unenroll(...).doit() +//! let r = hub.enterprises().set_account(...).doit() +//! let r = hub.enterprises().enroll(...).doit() +//! let r = hub.enterprises().delete(...).doit() +//! let r = hub.enterprises().get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-androidenterprise1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-androidenterprise1" as androidenterprise1; +//! use androidenterprise1::Enterprise; +//! use androidenterprise1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use androidenterprise1::AndroidEnterprise; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Enterprise = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.enterprises().insert(&req, "token") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage corporate Android devices + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/androidenterprise", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AndroidEnterprise related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Enterprise; +/// use androidenterprise1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Enterprise = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().insert(&req, "token") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AndroidEnterprise { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AndroidEnterprise {} + +impl<'a, C, NC, A> AndroidEnterprise + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AndroidEnterprise { + AndroidEnterprise { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn collections(&'a self) -> CollectionMethods<'a, C, NC, A> { + CollectionMethods { hub: &self } + } + pub fn collectionviewers(&'a self) -> CollectionviewerMethods<'a, C, NC, A> { + CollectionviewerMethods { hub: &self } + } + pub fn devices(&'a self) -> DeviceMethods<'a, C, NC, A> { + DeviceMethods { hub: &self } + } + pub fn enterprises(&'a self) -> EnterpriseMethods<'a, C, NC, A> { + EnterpriseMethods { hub: &self } + } + pub fn entitlements(&'a self) -> EntitlementMethods<'a, C, NC, A> { + EntitlementMethods { hub: &self } + } + pub fn grouplicenses(&'a self) -> GrouplicenseMethods<'a, C, NC, A> { + GrouplicenseMethods { hub: &self } + } + pub fn grouplicenseusers(&'a self) -> GrouplicenseuserMethods<'a, C, NC, A> { + GrouplicenseuserMethods { hub: &self } + } + pub fn installs(&'a self) -> InstallMethods<'a, C, NC, A> { + InstallMethods { hub: &self } + } + pub fn permissions(&'a self) -> PermissionMethods<'a, C, NC, A> { + PermissionMethods { hub: &self } + } + pub fn products(&'a self) -> ProductMethods<'a, C, NC, A> { + ProductMethods { hub: &self } + } + pub fn users(&'a self) -> UserMethods<'a, C, NC, A> { + UserMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Represents the list of app restrictions available to be pre-configured for the product. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get app restrictions schema products](struct.ProductGetAppRestrictionsSchemaCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AppRestrictionsSchema { + /// The set of restrictions that make up this schema. + pub restrictions: Vec, +} + +impl ResponseResult for AppRestrictionsSchema {} + + +/// A restriction in the App Restriction Schema represents a piece of configuration that may be pre-applied. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AppRestrictionsSchemaRestriction { + /// The type of the restriction. + #[serde(alias="restrictionType")] + pub restriction_type: String, + /// A longer description of the restriction, giving more detail of what it affects. + pub description: String, + /// The unique key that the product uses to identify the restriction, e.g. "com.google.android.gm.fieldname". + pub key: String, + /// The name of the restriction. + pub title: String, + /// For choice or multiselect restrictions, the list of possible entries' human-readable names. + pub entry: Vec, + /// The default value of the restriction. + #[serde(alias="defaultValue")] + pub default_value: AppRestrictionsSchemaRestrictionRestrictionValue, + /// For choice or multiselect restrictions, the list of possible entries' machine-readable values. + #[serde(alias="entryValue")] + pub entry_value: Vec, +} + +impl Part for AppRestrictionsSchemaRestriction {} + + +/// A typed value for the restriction. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AppRestrictionsSchemaRestrictionRestrictionValue { + /// The boolean value - this will only be present if type is bool. + #[serde(alias="valueBool")] + pub value_bool: bool, + /// The integer value - this will only be present if type is integer. + #[serde(alias="valueInteger")] + pub value_integer: i32, + /// The type of the value being provided. + #[serde(alias="type")] + pub type_: String, + /// The list of string values - this will only be present if type is multiselect. + #[serde(alias="valueMultiselect")] + pub value_multiselect: Vec, + /// The string value - this will be present for types string, choice and hidden. + #[serde(alias="valueString")] + pub value_string: String, +} + +impl Part for AppRestrictionsSchemaRestrictionRestrictionValue {} + + +/// The matching enterprise resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list enterprises](struct.EnterpriseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EnterprisesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#enterprisesListResponse". + pub kind: String, + /// An enterprise. + pub enterprise: Vec, +} + +impl ResponseResult for EnterprisesListResponse {} + + +/// The existence of an entitlement resource means that a user has the right to use a particular app on any of their devices. This might be because the app is free or because they have been allocated a license to the app from a group license purchased by the enterprise. +/// +/// It should always be true that a user has an app installed on one of their devices only if they have an entitlement to it. So if an entitlement is deleted, the app will be uninstalled from all devices. Similarly if the user installs an app (and is permitted to do so), or the MDM triggers an install of the app, an entitlement to that app is automatically created. If this is impossible - e.g. the enterprise has not purchased sufficient licenses - then installation fails. +/// +/// Note that entitlements are always user specific, not device specific; a user may have an entitlement even though they have not installed the app anywhere. Once they have an entitlement they can install the app on multiple devices. +/// +/// The API can be used to create an entitlement. If the app is a free app, a group license for that app is created. If it's a paid app, creating the entitlement consumes one license; it remains consumed until the entitlement is removed. Optionally an installation of the app on all the user's managed devices can be triggered at the time the entitlement is created. An entitlement cannot be created for an app if the app requires permissions that the enterprise has not yet accepted. +/// +/// Entitlements for paid apps that are due to purchases by the user on a non-managed profile will have "userPurchase" as entitlement reason; those entitlements cannot be removed via the API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch entitlements](struct.EntitlementPatchCall.html) (request|response) +/// * [list entitlements](struct.EntitlementListCall.html) (none) +/// * [delete entitlements](struct.EntitlementDeleteCall.html) (none) +/// * [update entitlements](struct.EntitlementUpdateCall.html) (request|response) +/// * [get entitlements](struct.EntitlementGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Entitlement { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#entitlement". + pub kind: Option, + /// The reason for the entitlement, e.g. "free" for free apps. This is temporary, it will be replaced by the acquisition kind field of group licenses. + pub reason: Option, + /// The ID of the product that the entitlement is for, e.g. "app:com.google.android.gm". + #[serde(alias="productId")] + pub product_id: Option, +} + +impl RequestValue for Entitlement {} +impl Resource for Entitlement {} +impl ResponseResult for Entitlement {} + + +/// The install resources for the device. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list installs](struct.InstallListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstallsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#installsListResponse". + pub kind: String, + /// An installation of an app for a user on a specific device. The existence of an install implies that the user must have an entitlement to the app. + pub install: Vec, +} + +impl ResponseResult for InstallsListResponse {} + + +/// The user resources for the collection. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list collectionviewers](struct.CollectionviewerListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CollectionViewersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionViewersListResponse". + pub kind: String, + /// A user of an enterprise. + pub user: Vec, +} + +impl ResponseResult for CollectionViewersListResponse {} + + +/// The device resources for the user. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list devices](struct.DeviceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DevicesListResponse { + /// A managed device. + pub device: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#devicesListResponse". + pub kind: String, +} + +impl ResponseResult for DevicesListResponse {} + + +/// The existence of an install resource indicates that an app is installed on a particular device (or that an install is pending). +/// +/// The API can be used to create an install resource using the update method. This triggers the actual install of the app on the device. If the user does not already have an entitlement for the app then an attempt is made to create one. If this fails (e.g. because the app is not free and there is no available license) then the creation of the install fails. +/// +/// The API can also be used to update an installed app. If the update method is used on an existing install then the app will be updated to the latest available version. +/// +/// Note that it is not possible to force the installation of a specific version of an app; the version code is read-only. +/// +/// If a user installs an app themselves (as permitted by the enterprise), then again an install resource and possibly an entitlement resource are automatically created. +/// +/// The API can also be used to delete an install resource, which triggers the removal of the app from the device. Note that deleting an install does not automatically remove the corresponding entitlement, even if there are no remaining installs. The install resource will also be deleted if the user uninstalls the app themselves. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch installs](struct.InstallPatchCall.html) (request|response) +/// * [list installs](struct.InstallListCall.html) (none) +/// * [delete installs](struct.InstallDeleteCall.html) (none) +/// * [update installs](struct.InstallUpdateCall.html) (request|response) +/// * [get installs](struct.InstallGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Install { + /// Install state. The state "installPending" means that an install request has recently been made and download to the device is in progress. The state "installed" means that the app has been installed. This field is read-only. + #[serde(alias="installState")] + pub install_state: Option, + /// The version of the installed product. Guaranteed to be set only if the install state is "installed". + #[serde(alias="versionCode")] + pub version_code: Option, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#install". + pub kind: Option, + /// The ID of the product that the install is for, e.g. "app:com.google.android.gm". + #[serde(alias="productId")] + pub product_id: Option, +} + +impl RequestValue for Install {} +impl Resource for Install {} +impl ResponseResult for Install {} + + +/// An enterprise resource represents a binding between an organisation and their MDM. +/// +/// To create an enterprise, an admin of the enterprise must first go through a Play for Work sign-up flow. At the end of this the admin will be presented with a token (a short opaque alphanumeric string). They must then present this to the MDM, who then supplies it to the enroll method. Until this is done the MDM will not have any access to the enterprise. +/// +/// After calling enroll the MDM should call setAccount to specify the service account that will be allowed to act on behalf of the enterprise, which will be required for access to the enterprise's data through this API. Only one call of setAccount is allowed for a given enterprise; the only way to change the account later is to unenroll the enterprise and enroll it again (obtaining a new token). +/// +/// The MDM can unenroll an enterprise in order to sever the binding between them. Re-enrolling an enterprise is possible, but requires a new token to be retrieved. Enterprises.unenroll requires the MDM's credentials (as enroll does), not the enterprise's. Enterprises.unenroll can only be used for enterprises that were previously enrolled with the enroll call. Any enterprises that were enrolled using the (deprecated) Enterprises.insert call must be unenrolled with Enterprises.delete and can then be re-enrolled using the Enterprises.enroll call. +/// +/// The ID for an enterprise is an opaque string. It is returned by insert and enroll and can also be retrieved if the enterprise's primary domain is known using the list method. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert enterprises](struct.EnterpriseInsertCall.html) (request|response) +/// * [list enterprises](struct.EnterpriseListCall.html) (none) +/// * [unenroll enterprises](struct.EnterpriseUnenrollCall.html) (none) +/// * [set account enterprises](struct.EnterpriseSetAccountCall.html) (none) +/// * [enroll enterprises](struct.EnterpriseEnrollCall.html) (request|response) +/// * [delete enterprises](struct.EnterpriseDeleteCall.html) (none) +/// * [get enterprises](struct.EnterpriseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Enterprise { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#enterprise". + pub kind: Option, + /// The enterprise's primary domain, e.g. "example.com". + #[serde(alias="primaryDomain")] + pub primary_domain: Option, + /// The unique ID for the enterprise. + pub id: Option, + /// The name of the enterprise, e.g. "Example Inc". + pub name: Option, +} + +impl RequestValue for Enterprise {} +impl Resource for Enterprise {} +impl ResponseResult for Enterprise {} + + +/// A UserToken is used by a user when setting up a managed device or profile with their work account on a device. When the user enters their email address and token (activation code) the appropriate MDM app can be automatically downloaded. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generate token users](struct.UserGenerateTokenCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserToken { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#userToken". + pub kind: String, + /// The unique ID for the user. + #[serde(alias="userId")] + pub user_id: String, + /// The token (activation code) to be entered by the user. This consists of a sequence of decimal digits. Note that the leading digit may be 0. + pub token: String, +} + +impl ResponseResult for UserToken {} + + +/// Information about the permissions required by a specific app and whether they have been accepted by the enterprise. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update permissions products](struct.ProductUpdatePermissionCall.html) (request|response) +/// * [get permissions products](struct.ProductGetPermissionCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductPermissions { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#productPermissions". + pub kind: Option, + /// The permissions required by the app. + pub permission: Option>, + /// The ID of the app that the permissions relate to, e.g. "app:com.google.android.gm". + #[serde(alias="productId")] + pub product_id: Option, +} + +impl RequestValue for ProductPermissions {} +impl ResponseResult for ProductPermissions {} + + +/// The state of a user's device, as accessed by the getState and setState methods on device resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get state devices](struct.DeviceGetStateCall.html) (response) +/// * [set state devices](struct.DeviceSetStateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeviceState { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#deviceState". + pub kind: Option, + /// The state of the Google account on the device. "enabled" indicates that the Google account on the device can be used to access Google services (including Google Play), while "disabled" means that it cannot. A new device is initially in the "disabled" state. + #[serde(alias="accountState")] + pub account_state: Option, +} + +impl RequestValue for DeviceState {} +impl ResponseResult for DeviceState {} + + +/// A product permissions resource represents the set of permissions required by a specific app and whether or not they have been accepted by an enterprise admin. +/// +/// The API can be used to read the set of permissions, and also to update the set to indicate that permissions have been accepted. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductPermission { + /// An opaque string uniquely identifying the permission. + #[serde(alias="permissionId")] + pub permission_id: String, + /// Whether the permission has been accepted or not. + pub state: String, +} + +impl Part for ProductPermission {} + + +/// A product represents an app in the Google Play Store that is available to at least some users in the enterprise. (Some apps are restricted to a single enterprise, and no information about them is made available outside that enterprise.) +/// +/// The information provided for each product (localized name, icon, link to the full Google Play details page) is intended to allow a basic representation of the product within an MDM user interface. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get products](struct.ProductGetCall.html) (response) +/// * [update permissions products](struct.ProductUpdatePermissionCall.html) (none) +/// * [get app restrictions schema products](struct.ProductGetAppRestrictionsSchemaCall.html) (none) +/// * [get permissions products](struct.ProductGetPermissionCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Product { + /// A link to an image that can be used as an icon for the product. + #[serde(alias="iconUrl")] + pub icon_url: String, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#product". + pub kind: String, + /// The name of the product. + pub title: String, + /// A link to the (consumer) Google Play details page for the product. + #[serde(alias="detailsUrl")] + pub details_url: String, + /// A link to the Google Play for Work details page for the product, for use by an Enterprise administrator. + #[serde(alias="workDetailsUrl")] + pub work_details_url: String, + /// The name of the author of the product (e.g. the app developer). + #[serde(alias="authorName")] + pub author_name: String, + /// A string of the form "app: + /// " - e.g. "app:com.google.android.gm" represents the GMail app. + #[serde(alias="productId")] + pub product_id: String, +} + +impl Resource for Product {} +impl ResponseResult for Product {} + + +/// A permission represents some extra capability, to be granted to an Android app, which requires explicit consent. An enterprise admin must consent to these permissions on behalf of their users before an entitlement for the app can be created. +/// +/// The permissions collection is read-only. The information provided for each permission (localized name and description) is intended to be used in the MDM user interface when obtaining consent from the enterprise. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get permissions](struct.PermissionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Permission { + /// An opaque string uniquely identifying the permission. + #[serde(alias="permissionId")] + pub permission_id: String, + /// A longer description of the permissions giving more details of what it affects. + pub description: String, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#permission". + pub kind: String, + /// The name of the permission. + pub name: String, +} + +impl Resource for Permission {} +impl ResponseResult for Permission {} + + +/// The entitlement resources for the user. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list entitlements](struct.EntitlementListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EntitlementsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#entitlementsListResponse". + pub kind: String, + /// An entitlement of a user to a product (e.g. an app). For example, a free app that they have installed, or a paid app that they have been allocated a license to. + pub entitlement: Vec, +} + +impl ResponseResult for EntitlementsListResponse {} + + +/// The matching user resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list users](struct.UserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#usersListResponse". + pub kind: String, + /// A user of an enterprise. + pub user: Vec, +} + +impl ResponseResult for UsersListResponse {} + + +/// A collection resource defines a named set of apps that is visible to a set of users in the Google Play Store app running on those users' managed devices. Those users can then install any of those apps if they wish (which will trigger creation of install and entitlement resources). A user cannot install an app on a managed device unless the app is listed in at least one collection that is visible to that user. +/// +/// Note that the API can be used to directly install an app regardless of whether it is in any collection - so an enterprise has a choice of either directly pushing apps to users, or allowing users to install apps if they want. Which is appropriate will depend on the enterprise's policies and the purpose of the apps concerned. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list collections](struct.CollectionListCall.html) (none) +/// * [patch collections](struct.CollectionPatchCall.html) (request|response) +/// * [insert collections](struct.CollectionInsertCall.html) (request|response) +/// * [get collections](struct.CollectionGetCall.html) (response) +/// * [delete collections](struct.CollectionDeleteCall.html) (none) +/// * [update collections](struct.CollectionUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Collection { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collection". + pub kind: Option, + /// Arbitrary unique ID, allocated by the API on creation. + #[serde(alias="collectionId")] + pub collection_id: Option, + /// A user-friendly name for the collection (should be unique), e.g. "Accounting apps". + pub name: Option, + /// Whether this collection is visible to all users, or only to the users that have been granted access through the collection_viewers api. Even if a collection is visible to allUsers, it is possible to add and remove viewers, but this will have no effect until the collection's visibility changes to viewersOnly. + pub visibility: Option, + /// The IDs of the products in the collection, in the order in which they should be displayed. + #[serde(alias="productId")] + pub product_id: Option>, +} + +impl RequestValue for Collection {} +impl Resource for Collection {} +impl ResponseResult for Collection {} + + +/// The collection resources for the enterprise. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list collections](struct.CollectionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CollectionsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionsListResponse". + pub kind: String, + /// An ordered collection of products which can be made visible on the Google Play Store app to a selected group of users. + pub collection: Vec, +} + +impl ResponseResult for CollectionsListResponse {} + + +/// A user resource represents an individual user within the enterprise's domain. +/// +/// Note that each user is associated with a Google account based on the user's corporate email address (which must be in one of the enterprise's domains). As part of installing an MDM app to manage a device the Google account must be provisioned to the device, and so the user resource must be created before that. This can be done using the Google Admin SDK Directory API. +/// +/// The ID for a user is an opaque string. It can be retrieved using the list method queried by the user's primary email address. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [revoke token users](struct.UserRevokeTokenCall.html) (none) +/// * [update collectionviewers](struct.CollectionviewerUpdateCall.html) (request|response) +/// * [patch collectionviewers](struct.CollectionviewerPatchCall.html) (request|response) +/// * [list users](struct.UserListCall.html) (none) +/// * [get collectionviewers](struct.CollectionviewerGetCall.html) (response) +/// * [generate token users](struct.UserGenerateTokenCall.html) (none) +/// * [get users](struct.UserGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct User { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#user". + pub kind: Option, + /// The user's primary email, e.g. "jsmith@example.com". + #[serde(alias="primaryEmail")] + pub primary_email: Option, + /// The unique ID for the user. + pub id: Option, +} + +impl RequestValue for User {} +impl Resource for User {} +impl ResponseResult for User {} + + +/// The user resources for the group license. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list grouplicenseusers](struct.GrouplicenseuserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GroupLicenseUsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicenseUsersListResponse". + pub kind: String, + /// A user of an enterprise. + pub user: Vec, +} + +impl ResponseResult for GroupLicenseUsersListResponse {} + + +/// A service account that can be used to authenticate as the enterprise to API calls that require such authentication. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set account enterprises](struct.EnterpriseSetAccountCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EnterpriseAccount { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#enterpriseAccount". + pub kind: Option, + /// The email address of the service account. + #[serde(alias="accountEmail")] + pub account_email: Option, +} + +impl RequestValue for EnterpriseAccount {} +impl ResponseResult for EnterpriseAccount {} + + +/// A device resource represents a mobile device managed by the MDM and belonging to a specific enterprise user. +/// +/// This collection cannot be modified via the API; it is automatically populated as devices are set up to be managed. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get devices](struct.DeviceGetCall.html) (response) +/// * [get state devices](struct.DeviceGetStateCall.html) (none) +/// * [list devices](struct.DeviceListCall.html) (none) +/// * [set state devices](struct.DeviceSetStateCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Device { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#device". + pub kind: String, + /// The Google Play Services Android ID for the device encoded as a lowercase hex string, e.g. "123456789abcdef0". + #[serde(alias="androidId")] + pub android_id: String, +} + +impl Resource for Device {} +impl ResponseResult for Device {} + + +/// A group license object indicates a product that an enterprise admin has approved for use in the enterprise. The product may be free or paid. For free products, a group license object is created in these cases: if the enterprise admin approves a product in Google Play, if the product is added to a collection, or if an entitlement for the product is created for a user via the API. For paid products, a group license object is only created as part of the first bulk purchase of that product in Google Play done by the enterprise admin. +/// +/// The API can be used to query group licenses; the available information includes the total number of licenses purchased (for paid products) and the total number of licenses that have been provisioned, i.e. the total number of user entitlements in existence for the product. +/// +/// Group license objects are never deleted; if e.g. a free app is added to a collection and then removed, the group license will remain, allowing to keep track of any remaining entitlements. An enterprise admin may indicate they are no longer interested in the group license by marking it as unapproved in Google Play. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get grouplicenses](struct.GrouplicenseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GroupLicense { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicense". + pub kind: String, + /// The number of purchased licenses (possibly in multiple purchases). If this field is omitted then there is no limit on the number of licenses that can be provisioned (e.g. if the acquisition kind is "free"). + #[serde(alias="numPurchased")] + pub num_purchased: i32, + /// The total number of provisioned licenses for this product. Returned by read operations, but ignored in write operations. + #[serde(alias="numProvisioned")] + pub num_provisioned: i32, + /// How this group license was acquired. "bulkPurchase" means that this group license object was created because the enterprise purchased licenses for this product; this is "free" otherwise (for free products). + #[serde(alias="acquisitionKind")] + pub acquisition_kind: String, + /// Whether the product to which this group license relates is currently approved by the enterprise, as either "approved" or "unapproved". Products are approved when a group license is first created, but this approval may be revoked by an enterprise admin via Google Play. Unapproved products will not be visible to end users in collections and new entitlements to them should not normally be created. + pub approval: String, + /// The ID of the product that the license is for, e.g. "app:com.google.android.gm". + #[serde(alias="productId")] + pub product_id: String, +} + +impl Resource for GroupLicense {} +impl ResponseResult for GroupLicense {} + + +/// The grouplicense resources for the enterprise. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list grouplicenses](struct.GrouplicenseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GroupLicensesListResponse { + /// A group license for a product approved for use in the enterprise. + #[serde(alias="groupLicense")] + pub group_license: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicensesListResponse". + pub kind: String, +} + +impl ResponseResult for GroupLicensesListResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *collectionviewer* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.collectionviewers(); +/// # } +/// ``` +pub struct CollectionviewerMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CollectionviewerMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Removes the user from the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. + pub fn delete(&self, enterprise_id: &str, collection_id: &str, user_id: &str) -> CollectionviewerDeleteCall<'a, C, NC, A> { + CollectionviewerDeleteCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds the user to the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. This method supports patch semantics. + pub fn patch(&self, request: &User, enterprise_id: &str, collection_id: &str, user_id: &str) -> CollectionviewerPatchCall<'a, C, NC, A> { + CollectionviewerPatchCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the ID of the user if they have been specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only these users will see the collection. + pub fn get(&self, enterprise_id: &str, collection_id: &str, user_id: &str) -> CollectionviewerGetCall<'a, C, NC, A> { + CollectionviewerGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the IDs of the users who have been specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only these users will see the collection. + pub fn list(&self, enterprise_id: &str, collection_id: &str) -> CollectionviewerListCall<'a, C, NC, A> { + CollectionviewerListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds the user to the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. + pub fn update(&self, request: &User, enterprise_id: &str, collection_id: &str, user_id: &str) -> CollectionviewerUpdateCall<'a, C, NC, A> { + CollectionviewerUpdateCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *user* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generate_token(...)`, `get(...)`, `list(...)` and `revoke_token(...)` +/// // to build up your call. +/// let rb = hub.users(); +/// # } +/// ``` +pub struct UserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Revokes a previously generated token (activation code) for the user. + pub fn revoke_token(&self, enterprise_id: &str, user_id: &str) -> UserRevokeTokenCall<'a, C, NC, A> { + UserRevokeTokenCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a user's details. + pub fn get(&self, enterprise_id: &str, user_id: &str) -> UserGetCall<'a, C, NC, A> { + UserGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Looks up a user by email address. + pub fn list(&self, enterprise_id: &str, email: &str) -> UserListCall<'a, C, NC, A> { + UserListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _email: email.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generates a token (activation code) to allow this user to configure their work account in the Android Setup Wizard. Revokes any previously generated token. + pub fn generate_token(&self, enterprise_id: &str, user_id: &str) -> UserGenerateTokenCall<'a, C, NC, A> { + UserGenerateTokenCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *install* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.installs(); +/// # } +/// ``` +pub struct InstallMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for InstallMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Requests to install the latest version of an app to a device. If the app is already installed then it is updated to the latest version if necessary. This method supports patch semantics. + pub fn patch(&self, request: &Install, enterprise_id: &str, user_id: &str, device_id: &str, install_id: &str) -> InstallPatchCall<'a, C, NC, A> { + InstallPatchCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _install_id: install_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves details of an installation of an app on a device. + pub fn get(&self, enterprise_id: &str, user_id: &str, device_id: &str, install_id: &str) -> InstallGetCall<'a, C, NC, A> { + InstallGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _install_id: install_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the details of all apps installed on the specified device. + pub fn list(&self, enterprise_id: &str, user_id: &str, device_id: &str) -> InstallListCall<'a, C, NC, A> { + InstallListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Requests to remove an app from a device. A call to get or list will still show the app as installed on the device until it is actually removed. + pub fn delete(&self, enterprise_id: &str, user_id: &str, device_id: &str, install_id: &str) -> InstallDeleteCall<'a, C, NC, A> { + InstallDeleteCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _install_id: install_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Requests to install the latest version of an app to a device. If the app is already installed then it is updated to the latest version if necessary. + pub fn update(&self, request: &Install, enterprise_id: &str, user_id: &str, device_id: &str, install_id: &str) -> InstallUpdateCall<'a, C, NC, A> { + InstallUpdateCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _install_id: install_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *device* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `get_state(...)`, `list(...)` and `set_state(...)` +/// // to build up your call. +/// let rb = hub.devices(); +/// # } +/// ``` +pub struct DeviceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DeviceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeviceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Sets whether a device is enabled or disabled for access by the user to Google services. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. + pub fn set_state(&self, request: &DeviceState, enterprise_id: &str, user_id: &str, device_id: &str) -> DeviceSetStateCall<'a, C, NC, A> { + DeviceSetStateCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves whether a device is enabled or disabled for access by the user to Google services. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. + pub fn get_state(&self, enterprise_id: &str, user_id: &str, device_id: &str) -> DeviceGetStateCall<'a, C, NC, A> { + DeviceGetStateCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the IDs of all of a user's devices. + pub fn list(&self, enterprise_id: &str, user_id: &str) -> DeviceListCall<'a, C, NC, A> { + DeviceListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the details of a device. + pub fn get(&self, enterprise_id: &str, user_id: &str, device_id: &str) -> DeviceGetCall<'a, C, NC, A> { + DeviceGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _device_id: device_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *enterprise* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `enroll(...)`, `get(...)`, `insert(...)`, `list(...)`, `set_account(...)` and `unenroll(...)` +/// // to build up your call. +/// let rb = hub.enterprises(); +/// # } +/// ``` +pub struct EnterpriseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for EnterpriseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Unenrolls an enterprise from the calling MDM. + pub fn unenroll(&self, enterprise_id: &str) -> EnterpriseUnenrollCall<'a, C, NC, A> { + EnterpriseUnenrollCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Establishes the binding between the MDM and an enterprise. This is now deprecated; use enroll instead. + pub fn insert(&self, request: &Enterprise, token: &str) -> EnterpriseInsertCall<'a, C, NC, A> { + EnterpriseInsertCall { + hub: self.hub, + _request: request.clone(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Looks up an enterprise by domain name. + pub fn list(&self, domain: &str) -> EnterpriseListCall<'a, C, NC, A> { + EnterpriseListCall { + hub: self.hub, + _domain: domain.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the name and domain of an enterprise. + pub fn get(&self, enterprise_id: &str) -> EnterpriseGetCall<'a, C, NC, A> { + EnterpriseGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Enrolls an enterprise with the calling MDM. + pub fn enroll(&self, request: &Enterprise, token: &str) -> EnterpriseEnrollCall<'a, C, NC, A> { + EnterpriseEnrollCall { + hub: self.hub, + _request: request.clone(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Set the account that will be used to authenticate to the API as the enterprise. + pub fn set_account(&self, request: &EnterpriseAccount, enterprise_id: &str) -> EnterpriseSetAccountCall<'a, C, NC, A> { + EnterpriseSetAccountCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the binding between the MDM and enterprise. This is now deprecated; use this to unenroll customers that were previously enrolled with the 'insert' call, then enroll them again with the 'enroll' call. + pub fn delete(&self, enterprise_id: &str) -> EnterpriseDeleteCall<'a, C, NC, A> { + EnterpriseDeleteCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *collection* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.collections(); +/// # } +/// ``` +pub struct CollectionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CollectionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates a new collection. + pub fn insert(&self, request: &Collection, enterprise_id: &str) -> CollectionInsertCall<'a, C, NC, A> { + CollectionInsertCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a collection. This method supports patch semantics. + pub fn patch(&self, request: &Collection, enterprise_id: &str, collection_id: &str) -> CollectionPatchCall<'a, C, NC, A> { + CollectionPatchCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a collection. + pub fn update(&self, request: &Collection, enterprise_id: &str, collection_id: &str) -> CollectionUpdateCall<'a, C, NC, A> { + CollectionUpdateCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the IDs of all the collections for an enterprise. + pub fn list(&self, enterprise_id: &str) -> CollectionListCall<'a, C, NC, A> { + CollectionListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the details of a collection. + pub fn get(&self, enterprise_id: &str, collection_id: &str) -> CollectionGetCall<'a, C, NC, A> { + CollectionGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a collection. + pub fn delete(&self, enterprise_id: &str, collection_id: &str) -> CollectionDeleteCall<'a, C, NC, A> { + CollectionDeleteCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _collection_id: collection_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *grouplicenseuser* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.grouplicenseusers(); +/// # } +/// ``` +pub struct GrouplicenseuserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GrouplicenseuserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GrouplicenseuserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the IDs of the users who have been granted entitlements under the license. + pub fn list(&self, enterprise_id: &str, group_license_id: &str) -> GrouplicenseuserListCall<'a, C, NC, A> { + GrouplicenseuserListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _group_license_id: group_license_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *entitlement* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.entitlements(); +/// # } +/// ``` +pub struct EntitlementMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for EntitlementMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Adds or updates an entitlement to an app for a user. + pub fn update(&self, request: &Entitlement, enterprise_id: &str, user_id: &str, entitlement_id: &str) -> EntitlementUpdateCall<'a, C, NC, A> { + EntitlementUpdateCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _entitlement_id: entitlement_id.to_string(), + _install: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List of all entitlements for the specified user. Only the ID is set. + pub fn list(&self, enterprise_id: &str, user_id: &str) -> EntitlementListCall<'a, C, NC, A> { + EntitlementListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves details of an entitlement. + pub fn get(&self, enterprise_id: &str, user_id: &str, entitlement_id: &str) -> EntitlementGetCall<'a, C, NC, A> { + EntitlementGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _entitlement_id: entitlement_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds or updates an entitlement to an app for a user. This method supports patch semantics. + pub fn patch(&self, request: &Entitlement, enterprise_id: &str, user_id: &str, entitlement_id: &str) -> EntitlementPatchCall<'a, C, NC, A> { + EntitlementPatchCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _entitlement_id: entitlement_id.to_string(), + _install: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes an entitlement to an app for a user and uninstalls it. + pub fn delete(&self, enterprise_id: &str, user_id: &str, entitlement_id: &str) -> EntitlementDeleteCall<'a, C, NC, A> { + EntitlementDeleteCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _user_id: user_id.to_string(), + _entitlement_id: entitlement_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *product* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `get_app_restrictions_schema(...)`, `get_permissions(...)` and `update_permissions(...)` +/// // to build up your call. +/// let rb = hub.products(); +/// # } +/// ``` +pub struct ProductMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProductMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the Android app permissions required by this app. + pub fn get_permissions(&self, enterprise_id: &str, product_id: &str) -> ProductGetPermissionCall<'a, C, NC, A> { + ProductGetPermissionCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _product_id: product_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves details of a product for display to an enterprise admin. + pub fn get(&self, enterprise_id: &str, product_id: &str) -> ProductGetCall<'a, C, NC, A> { + ProductGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _product_id: product_id.to_string(), + _language: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the schema defining app restrictions configurable for this product. All products have a schema, but this may be empty if no app restrictions are defined. + pub fn get_app_restrictions_schema(&self, enterprise_id: &str, product_id: &str) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> { + ProductGetAppRestrictionsSchemaCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _product_id: product_id.to_string(), + _language: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the set of Android app permissions for this app that have been accepted by the enterprise. + pub fn update_permissions(&self, request: &ProductPermissions, enterprise_id: &str, product_id: &str) -> ProductUpdatePermissionCall<'a, C, NC, A> { + ProductUpdatePermissionCall { + hub: self.hub, + _request: request.clone(), + _enterprise_id: enterprise_id.to_string(), + _product_id: product_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *grouplicense* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.grouplicenses(); +/// # } +/// ``` +pub struct GrouplicenseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GrouplicenseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GrouplicenseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves details of an enterprise's group license for a product. + pub fn get(&self, enterprise_id: &str, group_license_id: &str) -> GrouplicenseGetCall<'a, C, NC, A> { + GrouplicenseGetCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _group_license_id: group_license_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves IDs of all products for which the enterprise has a group license. + pub fn list(&self, enterprise_id: &str) -> GrouplicenseListCall<'a, C, NC, A> { + GrouplicenseListCall { + hub: self.hub, + _enterprise_id: enterprise_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *permission* resources. +/// It is not used directly, but through the `AndroidEnterprise` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidenterprise1" as androidenterprise1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidenterprise1::AndroidEnterprise; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.permissions(); +/// # } +/// ``` +pub struct PermissionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PermissionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves details of an Android app permission for display to an enterprise admin. + pub fn get(&self, permission_id: &str) -> PermissionGetCall<'a, C, NC, A> { + PermissionGetCall { + hub: self.hub, + _permission_id: permission_id.to_string(), + _language: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Removes the user from the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. +/// +/// A builder for the *delete* method supported by a *collectionviewer* resource. +/// It is not used directly, but through a `CollectionviewerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collectionviewers().delete("enterpriseId", "collectionId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionviewerDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _collection_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionviewerDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collectionviewers.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["enterpriseId", "collectionId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "collectionId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionviewerDeleteCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionviewerDeleteCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> CollectionviewerDeleteCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionviewerDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionviewerDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionviewerDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds the user to the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *collectionviewer* resource. +/// It is not used directly, but through a `CollectionviewerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: User = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collectionviewers().patch(&req, "enterpriseId", "collectionId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionviewerPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: User, + _enterprise_id: String, + _collection_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionviewerPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collectionviewers.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "collectionId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &User) -> CollectionviewerPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionviewerPatchCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionviewerPatchCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> CollectionviewerPatchCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionviewerPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionviewerPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionviewerPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the ID of the user if they have been specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only these users will see the collection. +/// +/// A builder for the *get* method supported by a *collectionviewer* resource. +/// It is not used directly, but through a `CollectionviewerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collectionviewers().get("enterpriseId", "collectionId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionviewerGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _collection_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionviewerGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collectionviewers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "collectionId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionviewerGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionviewerGetCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> CollectionviewerGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionviewerGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionviewerGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionviewerGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the IDs of the users who have been specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only these users will see the collection. +/// +/// A builder for the *list* method supported by a *collectionviewer* resource. +/// It is not used directly, but through a `CollectionviewerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collectionviewers().list("enterpriseId", "collectionId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionviewerListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _collection_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionviewerListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CollectionViewersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collectionviewers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "collectionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionviewerListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionviewerListCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionviewerListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionviewerListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionviewerListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds the user to the list of those specifically allowed to see the collection. If the collection's visibility is set to viewersOnly then only such users will see the collection. +/// +/// A builder for the *update* method supported by a *collectionviewer* resource. +/// It is not used directly, but through a `CollectionviewerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: User = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collectionviewers().update(&req, "enterpriseId", "collectionId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionviewerUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: User, + _enterprise_id: String, + _collection_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionviewerUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionviewerUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collectionviewers.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "collectionId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &User) -> CollectionviewerUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionviewerUpdateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionviewerUpdateCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> CollectionviewerUpdateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionviewerUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionviewerUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionviewerUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Revokes a previously generated token (activation code) for the user. +/// +/// A builder for the *revokeToken* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().revoke_token("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserRevokeTokenCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRevokeTokenCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRevokeTokenCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.users.revokeToken", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/token".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> UserRevokeTokenCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> UserRevokeTokenCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRevokeTokenCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRevokeTokenCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRevokeTokenCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a user's details. +/// +/// A builder for the *get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().get("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.users.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Looks up a user by email address. +/// +/// A builder for the *list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().list("enterpriseId", "email") +/// .doit(); +/// # } +/// ``` +pub struct UserListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _email: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UsersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.users.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("email", self._email.to_string())); + for &field in ["alt", "enterpriseId", "email"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *email* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The exact primary email address of the user to look up. + pub fn email(mut self, new_value: &str) -> UserListCall<'a, C, NC, A> { + self._email = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generates a token (activation code) to allow this user to configure their work account in the Android Setup Wizard. Revokes any previously generated token. +/// +/// A builder for the *generateToken* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().generate_token("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserGenerateTokenCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserGenerateTokenCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserGenerateTokenCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserToken)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.users.generateToken", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/token".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> UserGenerateTokenCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> UserGenerateTokenCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGenerateTokenCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserGenerateTokenCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserGenerateTokenCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Requests to install the latest version of an app to a device. If the app is already installed then it is updated to the latest version if necessary. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *install* resource. +/// It is not used directly, but through a `InstallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Install; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Install = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.installs().patch(&req, "enterpriseId", "userId", "deviceId", "installId") +/// .doit(); +/// # } +/// ``` +pub struct InstallPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Install, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _install_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstallPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Install)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.installs.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + params.push(("installId", self._install_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId", "installId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId"), ("{installId}", "installId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["enterpriseId", "userId", "deviceId", "installId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Install) -> InstallPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> InstallPatchCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> InstallPatchCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Android ID of the device. + pub fn device_id(mut self, new_value: &str) -> InstallPatchCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *install id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product represented by the install, e.g. "app:com.google.android.gm". + pub fn install_id(mut self, new_value: &str) -> InstallPatchCall<'a, C, NC, A> { + self._install_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstallPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstallPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstallPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves details of an installation of an app on a device. +/// +/// A builder for the *get* method supported by a *install* resource. +/// It is not used directly, but through a `InstallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.installs().get("enterpriseId", "userId", "deviceId", "installId") +/// .doit(); +/// # } +/// ``` +pub struct InstallGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _install_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstallGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Install)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.installs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + params.push(("installId", self._install_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId", "installId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId"), ("{installId}", "installId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["enterpriseId", "userId", "deviceId", "installId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> InstallGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> InstallGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Android ID of the device. + pub fn device_id(mut self, new_value: &str) -> InstallGetCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *install id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product represented by the install, e.g. "app:com.google.android.gm". + pub fn install_id(mut self, new_value: &str) -> InstallGetCall<'a, C, NC, A> { + self._install_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstallGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstallGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstallGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the details of all apps installed on the specified device. +/// +/// A builder for the *list* method supported by a *install* resource. +/// It is not used directly, but through a `InstallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.installs().list("enterpriseId", "userId", "deviceId") +/// .doit(); +/// # } +/// ``` +pub struct InstallListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstallListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstallsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.installs.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> InstallListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> InstallListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Android ID of the device. + pub fn device_id(mut self, new_value: &str) -> InstallListCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstallListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstallListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstallListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Requests to remove an app from a device. A call to get or list will still show the app as installed on the device until it is actually removed. +/// +/// A builder for the *delete* method supported by a *install* resource. +/// It is not used directly, but through a `InstallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.installs().delete("enterpriseId", "userId", "deviceId", "installId") +/// .doit(); +/// # } +/// ``` +pub struct InstallDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _install_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstallDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.installs.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + params.push(("installId", self._install_id.to_string())); + for &field in ["enterpriseId", "userId", "deviceId", "installId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId"), ("{installId}", "installId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["enterpriseId", "userId", "deviceId", "installId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> InstallDeleteCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> InstallDeleteCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Android ID of the device. + pub fn device_id(mut self, new_value: &str) -> InstallDeleteCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *install id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product represented by the install, e.g. "app:com.google.android.gm". + pub fn install_id(mut self, new_value: &str) -> InstallDeleteCall<'a, C, NC, A> { + self._install_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstallDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstallDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstallDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Requests to install the latest version of an app to a device. If the app is already installed then it is updated to the latest version if necessary. +/// +/// A builder for the *update* method supported by a *install* resource. +/// It is not used directly, but through a `InstallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Install; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Install = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.installs().update(&req, "enterpriseId", "userId", "deviceId", "installId") +/// .doit(); +/// # } +/// ``` +pub struct InstallUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Install, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _install_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstallUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstallUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Install)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.installs.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + params.push(("installId", self._install_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId", "installId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/installs/{installId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId"), ("{installId}", "installId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["enterpriseId", "userId", "deviceId", "installId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Install) -> InstallUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> InstallUpdateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> InstallUpdateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Android ID of the device. + pub fn device_id(mut self, new_value: &str) -> InstallUpdateCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *install id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product represented by the install, e.g. "app:com.google.android.gm". + pub fn install_id(mut self, new_value: &str) -> InstallUpdateCall<'a, C, NC, A> { + self._install_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstallUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstallUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstallUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets whether a device is enabled or disabled for access by the user to Google services. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. +/// +/// A builder for the *setState* method supported by a *device* resource. +/// It is not used directly, but through a `DeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::DeviceState; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DeviceState = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.devices().set_state(&req, "enterpriseId", "userId", "deviceId") +/// .doit(); +/// # } +/// ``` +pub struct DeviceSetStateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: DeviceState, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeviceSetStateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeviceSetStateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeviceState)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.devices.setState", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/state".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DeviceState) -> DeviceSetStateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> DeviceSetStateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> DeviceSetStateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the device. + pub fn device_id(mut self, new_value: &str) -> DeviceSetStateCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeviceSetStateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeviceSetStateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeviceSetStateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves whether a device is enabled or disabled for access by the user to Google services. The device state takes effect only if enforcing EMM policies on Android devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. +/// +/// A builder for the *getState* method supported by a *device* resource. +/// It is not used directly, but through a `DeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.devices().get_state("enterpriseId", "userId", "deviceId") +/// .doit(); +/// # } +/// ``` +pub struct DeviceGetStateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeviceGetStateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeviceGetStateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeviceState)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.devices.getState", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}/state".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> DeviceGetStateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> DeviceGetStateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the device. + pub fn device_id(mut self, new_value: &str) -> DeviceGetStateCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeviceGetStateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeviceGetStateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeviceGetStateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the IDs of all of a user's devices. +/// +/// A builder for the *list* method supported by a *device* resource. +/// It is not used directly, but through a `DeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.devices().list("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct DeviceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeviceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeviceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DevicesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.devices.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> DeviceListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> DeviceListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeviceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeviceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeviceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the details of a device. +/// +/// A builder for the *get* method supported by a *device* resource. +/// It is not used directly, but through a `DeviceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.devices().get("enterpriseId", "userId", "deviceId") +/// .doit(); +/// # } +/// ``` +pub struct DeviceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _device_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeviceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeviceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Device)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.devices.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("deviceId", self._device_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "deviceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/devices/{deviceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{deviceId}", "deviceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "deviceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> DeviceGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> DeviceGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *device id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the device. + pub fn device_id(mut self, new_value: &str) -> DeviceGetCall<'a, C, NC, A> { + self._device_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeviceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeviceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeviceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Unenrolls an enterprise from the calling MDM. +/// +/// A builder for the *unenroll* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().unenroll("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseUnenrollCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseUnenrollCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseUnenrollCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.unenroll", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/unenroll".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EnterpriseUnenrollCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseUnenrollCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseUnenrollCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseUnenrollCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Establishes the binding between the MDM and an enterprise. This is now deprecated; use enroll instead. +/// +/// A builder for the *insert* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Enterprise; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Enterprise = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().insert(&req, "token") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Enterprise, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Enterprise)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Enterprise) -> EnterpriseInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *token* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided by the enterprise to register the MDM. + pub fn token(mut self, new_value: &str) -> EnterpriseInsertCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Looks up an enterprise by domain name. +/// +/// A builder for the *list* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().list("domain") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _domain: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EnterprisesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("domain", self._domain.to_string())); + for &field in ["alt", "domain"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *domain* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The exact primary domain name of the enterprise to look up. + pub fn domain(mut self, new_value: &str) -> EnterpriseListCall<'a, C, NC, A> { + self._domain = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the name and domain of an enterprise. +/// +/// A builder for the *get* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().get("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Enterprise)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["alt", "enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EnterpriseGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Enrolls an enterprise with the calling MDM. +/// +/// A builder for the *enroll* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Enterprise; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Enterprise = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().enroll(&req, "token") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseEnrollCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Enterprise, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseEnrollCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseEnrollCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Enterprise)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.enroll", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/enroll".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Enterprise) -> EnterpriseEnrollCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *token* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided by the enterprise to register the MDM. + pub fn token(mut self, new_value: &str) -> EnterpriseEnrollCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseEnrollCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseEnrollCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseEnrollCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Set the account that will be used to authenticate to the API as the enterprise. +/// +/// A builder for the *setAccount* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::EnterpriseAccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EnterpriseAccount = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().set_account(&req, "enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseSetAccountCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: EnterpriseAccount, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseSetAccountCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseSetAccountCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EnterpriseAccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.setAccount", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["alt", "enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/account".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EnterpriseAccount) -> EnterpriseSetAccountCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EnterpriseSetAccountCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseSetAccountCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseSetAccountCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseSetAccountCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the binding between the MDM and enterprise. This is now deprecated; use this to unenroll customers that were previously enrolled with the 'insert' call, then enroll them again with the 'enroll' call. +/// +/// A builder for the *delete* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.enterprises().delete("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EnterpriseDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EnterpriseDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.enterprises.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EnterpriseDeleteCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new collection. +/// +/// A builder for the *insert* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Collection; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Collection = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().insert(&req, "enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Collection, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Collection)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["alt", "enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Collection) -> CollectionInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionInsertCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a collection. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Collection; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Collection = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().patch(&req, "enterpriseId", "collectionId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Collection, + _enterprise_id: String, + _collection_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Collection)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "collectionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Collection) -> CollectionPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionPatchCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionPatchCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a collection. +/// +/// A builder for the *update* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Collection; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Collection = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().update(&req, "enterpriseId", "collectionId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Collection, + _enterprise_id: String, + _collection_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Collection)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "collectionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Collection) -> CollectionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionUpdateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionUpdateCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the IDs of all the collections for an enterprise. +/// +/// A builder for the *list* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().list("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CollectionsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["alt", "enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the details of a collection. +/// +/// A builder for the *get* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().get("enterpriseId", "collectionId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _collection_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Collection)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + for &field in ["alt", "enterpriseId", "collectionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "collectionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionGetCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a collection. +/// +/// A builder for the *delete* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.collections().delete("enterpriseId", "collectionId") +/// .doit(); +/// # } +/// ``` +pub struct CollectionDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _collection_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CollectionDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CollectionDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.collections.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("collectionId", self._collection_id.to_string())); + for &field in ["enterpriseId", "collectionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/collections/{collectionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{collectionId}", "collectionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "collectionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *collection id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the collection. + pub fn collection_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, NC, A> { + self._collection_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CollectionDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CollectionDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the IDs of the users who have been granted entitlements under the license. +/// +/// A builder for the *list* method supported by a *grouplicenseuser* resource. +/// It is not used directly, but through a `GrouplicenseuserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.grouplicenseusers().list("enterpriseId", "groupLicenseId") +/// .doit(); +/// # } +/// ``` +pub struct GrouplicenseuserListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _group_license_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GrouplicenseuserListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GrouplicenseuserListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GroupLicenseUsersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.grouplicenseusers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("groupLicenseId", self._group_license_id.to_string())); + for &field in ["alt", "enterpriseId", "groupLicenseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/groupLicenses/{groupLicenseId}/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{groupLicenseId}", "groupLicenseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "groupLicenseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> GrouplicenseuserListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *group license id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product the group license is for, e.g. "app:com.google.android.gm". + pub fn group_license_id(mut self, new_value: &str) -> GrouplicenseuserListCall<'a, C, NC, A> { + self._group_license_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GrouplicenseuserListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GrouplicenseuserListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GrouplicenseuserListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds or updates an entitlement to an app for a user. +/// +/// A builder for the *update* method supported by a *entitlement* resource. +/// It is not used directly, but through a `EntitlementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Entitlement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Entitlement = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.entitlements().update(&req, "enterpriseId", "userId", "entitlementId") +/// .install(false) +/// .doit(); +/// # } +/// ``` +pub struct EntitlementUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Entitlement, + _enterprise_id: String, + _user_id: String, + _entitlement_id: String, + _install: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EntitlementUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Entitlement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.entitlements.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("entitlementId", self._entitlement_id.to_string())); + if let Some(value) = self._install { + params.push(("install", value.to_string())); + } + for &field in ["alt", "enterpriseId", "userId", "entitlementId", "install"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{entitlementId}", "entitlementId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "entitlementId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Entitlement) -> EntitlementUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EntitlementUpdateCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> EntitlementUpdateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *entitlement id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the entitlement, e.g. "app:com.google.android.gm". + pub fn entitlement_id(mut self, new_value: &str) -> EntitlementUpdateCall<'a, C, NC, A> { + self._entitlement_id = new_value.to_string(); + self + } + /// Sets the *install* query property to the given value. + /// + /// + /// Set to true to also install the product on all the user's devices where possible. Failure to install on one or more devices will not prevent this operation from returning successfully, as long as the entitlement was successfully assigned to the user. + pub fn install(mut self, new_value: bool) -> EntitlementUpdateCall<'a, C, NC, A> { + self._install = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EntitlementUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EntitlementUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EntitlementUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List of all entitlements for the specified user. Only the ID is set. +/// +/// A builder for the *list* method supported by a *entitlement* resource. +/// It is not used directly, but through a `EntitlementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.entitlements().list("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct EntitlementListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EntitlementListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EntitlementsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.entitlements.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/entitlements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EntitlementListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> EntitlementListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EntitlementListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EntitlementListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EntitlementListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves details of an entitlement. +/// +/// A builder for the *get* method supported by a *entitlement* resource. +/// It is not used directly, but through a `EntitlementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.entitlements().get("enterpriseId", "userId", "entitlementId") +/// .doit(); +/// # } +/// ``` +pub struct EntitlementGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _entitlement_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EntitlementGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Entitlement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.entitlements.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("entitlementId", self._entitlement_id.to_string())); + for &field in ["alt", "enterpriseId", "userId", "entitlementId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{entitlementId}", "entitlementId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "entitlementId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EntitlementGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> EntitlementGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *entitlement id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the entitlement, e.g. "app:com.google.android.gm". + pub fn entitlement_id(mut self, new_value: &str) -> EntitlementGetCall<'a, C, NC, A> { + self._entitlement_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EntitlementGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EntitlementGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EntitlementGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds or updates an entitlement to an app for a user. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *entitlement* resource. +/// It is not used directly, but through a `EntitlementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::Entitlement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Entitlement = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.entitlements().patch(&req, "enterpriseId", "userId", "entitlementId") +/// .install(true) +/// .doit(); +/// # } +/// ``` +pub struct EntitlementPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: Entitlement, + _enterprise_id: String, + _user_id: String, + _entitlement_id: String, + _install: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EntitlementPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Entitlement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.entitlements.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("entitlementId", self._entitlement_id.to_string())); + if let Some(value) = self._install { + params.push(("install", value.to_string())); + } + for &field in ["alt", "enterpriseId", "userId", "entitlementId", "install"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{entitlementId}", "entitlementId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "entitlementId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Entitlement) -> EntitlementPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EntitlementPatchCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> EntitlementPatchCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *entitlement id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the entitlement, e.g. "app:com.google.android.gm". + pub fn entitlement_id(mut self, new_value: &str) -> EntitlementPatchCall<'a, C, NC, A> { + self._entitlement_id = new_value.to_string(); + self + } + /// Sets the *install* query property to the given value. + /// + /// + /// Set to true to also install the product on all the user's devices where possible. Failure to install on one or more devices will not prevent this operation from returning successfully, as long as the entitlement was successfully assigned to the user. + pub fn install(mut self, new_value: bool) -> EntitlementPatchCall<'a, C, NC, A> { + self._install = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EntitlementPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EntitlementPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EntitlementPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes an entitlement to an app for a user and uninstalls it. +/// +/// A builder for the *delete* method supported by a *entitlement* resource. +/// It is not used directly, but through a `EntitlementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.entitlements().delete("enterpriseId", "userId", "entitlementId") +/// .doit(); +/// # } +/// ``` +pub struct EntitlementDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _user_id: String, + _entitlement_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EntitlementDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EntitlementDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.entitlements.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("userId", self._user_id.to_string())); + params.push(("entitlementId", self._entitlement_id.to_string())); + for &field in ["enterpriseId", "userId", "entitlementId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/users/{userId}/entitlements/{entitlementId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{userId}", "userId"), ("{entitlementId}", "entitlementId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["enterpriseId", "userId", "entitlementId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> EntitlementDeleteCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user. + pub fn user_id(mut self, new_value: &str) -> EntitlementDeleteCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *entitlement id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the entitlement, e.g. "app:com.google.android.gm". + pub fn entitlement_id(mut self, new_value: &str) -> EntitlementDeleteCall<'a, C, NC, A> { + self._entitlement_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EntitlementDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EntitlementDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EntitlementDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the Android app permissions required by this app. +/// +/// A builder for the *getPermissions* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().get_permissions("enterpriseId", "productId") +/// .doit(); +/// # } +/// ``` +pub struct ProductGetPermissionCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _product_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductGetPermissionCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductGetPermissionCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductPermissions)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.products.getPermissions", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("productId", self._product_id.to_string())); + for &field in ["alt", "enterpriseId", "productId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/products/{productId}/permissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> ProductGetPermissionCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductGetPermissionCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductGetPermissionCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductGetPermissionCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductGetPermissionCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves details of a product for display to an enterprise admin. +/// +/// A builder for the *get* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().get("enterpriseId", "productId") +/// .language("labore") +/// .doit(); +/// # } +/// ``` +pub struct ProductGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _product_id: String, + _language: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Product)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.products.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("productId", self._product_id.to_string())); + if let Some(value) = self._language { + params.push(("language", value.to_string())); + } + for &field in ["alt", "enterpriseId", "productId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/products/{productId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> ProductGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product, e.g. "app:com.google.android.gm". + pub fn product_id(mut self, new_value: &str) -> ProductGetCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *language* query property to the given value. + /// + /// + /// The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). + pub fn language(mut self, new_value: &str) -> ProductGetCall<'a, C, NC, A> { + self._language = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the schema defining app restrictions configurable for this product. All products have a schema, but this may be empty if no app restrictions are defined. +/// +/// A builder for the *getAppRestrictionsSchema* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().get_app_restrictions_schema("enterpriseId", "productId") +/// .language("sadipscing") +/// .doit(); +/// # } +/// ``` +pub struct ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _product_id: String, + _language: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppRestrictionsSchema)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.products.getAppRestrictionsSchema", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("productId", self._product_id.to_string())); + if let Some(value) = self._language { + params.push(("language", value.to_string())); + } + for &field in ["alt", "enterpriseId", "productId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/products/{productId}/appRestrictionsSchema".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *language* query property to the given value. + /// + /// + /// The BCP47 tag for the user's preferred language (e.g. "en-US", "de"). + pub fn language(mut self, new_value: &str) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> { + self._language = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductGetAppRestrictionsSchemaCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the set of Android app permissions for this app that have been accepted by the enterprise. +/// +/// A builder for the *updatePermissions* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// use androidenterprise1::ProductPermissions; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProductPermissions = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().update_permissions(&req, "enterpriseId", "productId") +/// .doit(); +/// # } +/// ``` +pub struct ProductUpdatePermissionCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: ProductPermissions, + _enterprise_id: String, + _product_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductUpdatePermissionCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductUpdatePermissionCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductPermissions)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.products.updatePermissions", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("productId", self._product_id.to_string())); + for &field in ["alt", "enterpriseId", "productId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/products/{productId}/permissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProductPermissions) -> ProductUpdatePermissionCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> ProductUpdatePermissionCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductUpdatePermissionCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductUpdatePermissionCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductUpdatePermissionCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductUpdatePermissionCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves details of an enterprise's group license for a product. +/// +/// A builder for the *get* method supported by a *grouplicense* resource. +/// It is not used directly, but through a `GrouplicenseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.grouplicenses().get("enterpriseId", "groupLicenseId") +/// .doit(); +/// # } +/// ``` +pub struct GrouplicenseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _group_license_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GrouplicenseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GrouplicenseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GroupLicense)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.grouplicenses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + params.push(("groupLicenseId", self._group_license_id.to_string())); + for &field in ["alt", "enterpriseId", "groupLicenseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/groupLicenses/{groupLicenseId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId"), ("{groupLicenseId}", "groupLicenseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["enterpriseId", "groupLicenseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> GrouplicenseGetCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *group license id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product the group license is for, e.g. "app:com.google.android.gm". + pub fn group_license_id(mut self, new_value: &str) -> GrouplicenseGetCall<'a, C, NC, A> { + self._group_license_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GrouplicenseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GrouplicenseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GrouplicenseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves IDs of all products for which the enterprise has a group license. +/// +/// A builder for the *list* method supported by a *grouplicense* resource. +/// It is not used directly, but through a `GrouplicenseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.grouplicenses().list("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct GrouplicenseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GrouplicenseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GrouplicenseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GroupLicensesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.grouplicenses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("enterpriseId", self._enterprise_id.to_string())); + for &field in ["alt", "enterpriseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/enterprises/{enterpriseId}/groupLicenses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{enterpriseId}", "enterpriseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["enterpriseId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *enterprise id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the enterprise. + pub fn enterprise_id(mut self, new_value: &str) -> GrouplicenseListCall<'a, C, NC, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GrouplicenseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GrouplicenseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GrouplicenseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves details of an Android app permission for display to an enterprise admin. +/// +/// A builder for the *get* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidenterprise1" as androidenterprise1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidenterprise1::AndroidEnterprise; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidEnterprise::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().get("permissionId") +/// .language("eirmod") +/// .doit(); +/// # } +/// ``` +pub struct PermissionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _permission_id: String, + _language: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Permission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidenterprise.permissions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("permissionId", self._permission_id.to_string())); + if let Some(value) = self._language { + params.push(("language", value.to_string())); + } + for &field in ["alt", "permissionId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidenterprise/v1/permissions/{permissionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{permissionId}", "permissionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["permissionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *permission id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the permission. + pub fn permission_id(mut self, new_value: &str) -> PermissionGetCall<'a, C, NC, A> { + self._permission_id = new_value.to_string(); + self + } + /// Sets the *language* query property to the given value. + /// + /// + /// The BCP47 tag for the user's preferred language (e.g. "en-US", "de") + pub fn language(mut self, new_value: &str) -> PermissionGetCall<'a, C, NC, A> { + self._language = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/androidpublisher2/Cargo.toml b/gen/androidpublisher2/Cargo.toml new file mode 100644 index 0000000000..96af8d79b9 --- /dev/null +++ b/gen/androidpublisher2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-androidpublisher2" +version = "0.1.0+20150128" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Android Publisher (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/androidpublisher2" +homepage = "https://developers.google.com/android-publisher" +documentation = "http://byron.github.io/google-apis-rs/google-androidpublisher2" +license = "MIT" +keywords = ["androidpublisher", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/androidpublisher2/LICENSE.md b/gen/androidpublisher2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/androidpublisher2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/androidpublisher2/README.md b/gen/androidpublisher2/README.md new file mode 100644 index 0000000000..fa834a47c4 --- /dev/null +++ b/gen/androidpublisher2/README.md @@ -0,0 +1,183 @@ + +The `google-androidpublisher2` library allows access to all features of the *Google Android Publisher* service. + +This documentation was generated from *Android Publisher* crate version *0.1.0+20150128*, where *20150128* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Android Publisher* *v2* API can be found at the +[official documentation site](https://developers.google.com/android-publisher). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.AndroidPublisher.html) ... + +* edits + * [*apklistings delete*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingDeleteCall.html), [*apklistings deleteall*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingDeleteallCall.html), [*apklistings get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingGetCall.html), [*apklistings list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingListCall.html), [*apklistings patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingPatchCall.html), [*apklistings update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApklistingUpdateCall.html), [*apks addexternallyhosted*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApkAddexternallyhostedCall.html), [*apks list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApkListCall.html), [*apks upload*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApkUploadCall.html), [*commit*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditCommitCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditDeleteCall.html), [*details get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditDetailGetCall.html), [*details patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditDetailPatchCall.html), [*details update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditDetailUpdateCall.html), [*expansionfiles get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditExpansionfileGetCall.html), [*expansionfiles patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditExpansionfilePatchCall.html), [*expansionfiles update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditExpansionfileUpdateCall.html), [*expansionfiles upload*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditExpansionfileUploadCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditGetCall.html), [*images delete*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditImageDeleteCall.html), [*images deleteall*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditImageDeleteallCall.html), [*images list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditImageListCall.html), [*images upload*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditImageUploadCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditInsertCall.html), [*listings delete*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingDeleteCall.html), [*listings deleteall*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingDeleteallCall.html), [*listings get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingGetCall.html), [*listings list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingListCall.html), [*listings patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingPatchCall.html), [*listings update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditListingUpdateCall.html), [*testers get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTesterGetCall.html), [*testers patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTesterPatchCall.html), [*testers update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTesterUpdateCall.html), [*tracks get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTrackGetCall.html), [*tracks list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTrackListCall.html), [*tracks patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTrackPatchCall.html), [*tracks update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditTrackUpdateCall.html) and [*validate*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditValidateCall.html) +* inappproducts + * [*batch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductBatchCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.InappproductUpdateCall.html) +* purchases + * [*products get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseProductGetCall.html), [*subscriptions cancel*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseSubscriptionCancelCall.html), [*subscriptions defer*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseSubscriptionDeferCall.html), [*subscriptions get*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseSubscriptionGetCall.html), [*subscriptions refund*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseSubscriptionRefundCall.html) and [*subscriptions revoke*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.PurchaseSubscriptionRevokeCall.html) + + +Upload supported by ... + +* [*images upload edits*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditImageUploadCall.html) +* [*expansionfiles upload edits*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditExpansionfileUploadCall.html) +* [*apks upload edits*](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.EditApkUploadCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-androidpublisher2/struct.AndroidPublisher.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.inappproducts().patch(...).doit() +let r = hub.inappproducts().insert(...).doit() +let r = hub.inappproducts().get(...).doit() +let r = hub.inappproducts().update(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-androidpublisher2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-androidpublisher2" as androidpublisher2; +use androidpublisher2::InAppProduct; +use androidpublisher2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use androidpublisher2::AndroidPublisher; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: InAppProduct = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.inappproducts().patch(&req, "packageName", "sku") + .auto_convert_missing_prices(false) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-androidpublisher2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-androidpublisher2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-androidpublisher2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-androidpublisher2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **androidpublisher2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/androidpublisher2/src/cmn.rs b/gen/androidpublisher2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/androidpublisher2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/androidpublisher2/src/lib.rs b/gen/androidpublisher2/src/lib.rs new file mode 100644 index 0000000000..5d9c6352f1 --- /dev/null +++ b/gen/androidpublisher2/src/lib.rs @@ -0,0 +1,15753 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Android Publisher* crate version *0.1.0+20150128*, where *20150128* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Android Publisher* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/android-publisher). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/androidpublisher2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AndroidPublisher.html) ... +//! +//! * edits +//! * [*apklistings delete*](struct.EditApklistingDeleteCall.html), [*apklistings deleteall*](struct.EditApklistingDeleteallCall.html), [*apklistings get*](struct.EditApklistingGetCall.html), [*apklistings list*](struct.EditApklistingListCall.html), [*apklistings patch*](struct.EditApklistingPatchCall.html), [*apklistings update*](struct.EditApklistingUpdateCall.html), [*apks addexternallyhosted*](struct.EditApkAddexternallyhostedCall.html), [*apks list*](struct.EditApkListCall.html), [*apks upload*](struct.EditApkUploadCall.html), [*commit*](struct.EditCommitCall.html), [*delete*](struct.EditDeleteCall.html), [*details get*](struct.EditDetailGetCall.html), [*details patch*](struct.EditDetailPatchCall.html), [*details update*](struct.EditDetailUpdateCall.html), [*expansionfiles get*](struct.EditExpansionfileGetCall.html), [*expansionfiles patch*](struct.EditExpansionfilePatchCall.html), [*expansionfiles update*](struct.EditExpansionfileUpdateCall.html), [*expansionfiles upload*](struct.EditExpansionfileUploadCall.html), [*get*](struct.EditGetCall.html), [*images delete*](struct.EditImageDeleteCall.html), [*images deleteall*](struct.EditImageDeleteallCall.html), [*images list*](struct.EditImageListCall.html), [*images upload*](struct.EditImageUploadCall.html), [*insert*](struct.EditInsertCall.html), [*listings delete*](struct.EditListingDeleteCall.html), [*listings deleteall*](struct.EditListingDeleteallCall.html), [*listings get*](struct.EditListingGetCall.html), [*listings list*](struct.EditListingListCall.html), [*listings patch*](struct.EditListingPatchCall.html), [*listings update*](struct.EditListingUpdateCall.html), [*testers get*](struct.EditTesterGetCall.html), [*testers patch*](struct.EditTesterPatchCall.html), [*testers update*](struct.EditTesterUpdateCall.html), [*tracks get*](struct.EditTrackGetCall.html), [*tracks list*](struct.EditTrackListCall.html), [*tracks patch*](struct.EditTrackPatchCall.html), [*tracks update*](struct.EditTrackUpdateCall.html) and [*validate*](struct.EditValidateCall.html) +//! * inappproducts +//! * [*batch*](struct.InappproductBatchCall.html), [*delete*](struct.InappproductDeleteCall.html), [*get*](struct.InappproductGetCall.html), [*insert*](struct.InappproductInsertCall.html), [*list*](struct.InappproductListCall.html), [*patch*](struct.InappproductPatchCall.html) and [*update*](struct.InappproductUpdateCall.html) +//! * purchases +//! * [*products get*](struct.PurchaseProductGetCall.html), [*subscriptions cancel*](struct.PurchaseSubscriptionCancelCall.html), [*subscriptions defer*](struct.PurchaseSubscriptionDeferCall.html), [*subscriptions get*](struct.PurchaseSubscriptionGetCall.html), [*subscriptions refund*](struct.PurchaseSubscriptionRefundCall.html) and [*subscriptions revoke*](struct.PurchaseSubscriptionRevokeCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*images upload edits*](struct.EditImageUploadCall.html) +//! * [*expansionfiles upload edits*](struct.EditExpansionfileUploadCall.html) +//! * [*apks upload edits*](struct.EditApkUploadCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AndroidPublisher.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.inappproducts().patch(...).doit() +//! let r = hub.inappproducts().insert(...).doit() +//! let r = hub.inappproducts().get(...).doit() +//! let r = hub.inappproducts().update(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-androidpublisher2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-androidpublisher2" as androidpublisher2; +//! use androidpublisher2::InAppProduct; +//! use androidpublisher2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use androidpublisher2::AndroidPublisher; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: InAppProduct = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.inappproducts().patch(&req, "packageName", "sku") +//! .auto_convert_missing_prices(true) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your Google Play Android Developer account + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/androidpublisher", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AndroidPublisher related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::InAppProduct; +/// use androidpublisher2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidpublisher2::AndroidPublisher; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InAppProduct = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().patch(&req, "packageName", "sku") +/// .auto_convert_missing_prices(true) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AndroidPublisher { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AndroidPublisher {} + +impl<'a, C, NC, A> AndroidPublisher + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AndroidPublisher { + AndroidPublisher { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn edits(&'a self) -> EditMethods<'a, C, NC, A> { + EditMethods { hub: &self } + } + pub fn inappproducts(&'a self) -> InappproductMethods<'a, C, NC, A> { + InappproductMethods { hub: &self } + } + pub fn purchases(&'a self) -> PurchaseMethods<'a, C, NC, A> { + PurchaseMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InappproductsUpdateResponse { + /// no description provided + pub inappproduct: InAppProduct, +} + +impl Part for InappproductsUpdateResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch inappproducts](struct.InappproductPatchCall.html) (request|response) +/// * [insert inappproducts](struct.InappproductInsertCall.html) (request|response) +/// * [get inappproducts](struct.InappproductGetCall.html) (response) +/// * [update inappproducts](struct.InappproductUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InAppProduct { + /// The stock-keeping-unit (SKU) of the product, unique within an app. + pub sku: Option, + /// no description provided + pub status: Option, + /// The period of the subscription (if any), i.e. period at which payments must happen. Defined as ISO 8601 duration, i.e. "P1M" for 1 month period. + #[serde(alias="subscriptionPeriod")] + pub subscription_period: Option, + /// Definition of a season for a seasonal subscription. Can be defined only for yearly subscriptions. + pub season: Option, + /// The package name of the parent app. + #[serde(alias="packageName")] + pub package_name: Option, + /// List of localized title and description data. + pub listings: Option>, + /// Trial period, specified in ISO 8601 format. Acceptable values are anything between "P7D" (seven days) and "P999D" (999 days). Seasonal subscriptions cannot have a trial period. + #[serde(alias="trialPeriod")] + pub trial_period: Option, + /// Purchase type enum value. Unmodifiable after creation. + #[serde(alias="purchaseType")] + pub purchase_type: Option, + /// The default language of the localized data, as defined by BCP 47. e.g. "en-US", "en-GB". + #[serde(alias="defaultLanguage")] + pub default_language: Option, + /// Prices per buyer region. None of these prices should be zero. In-app products can never be free. + pub prices: Option>, + /// Default price cannot be zero. In-app products can never be free. Default price is always in the developer's Checkout merchant currency. + #[serde(alias="defaultPrice")] + pub default_price: Option, +} + +impl RequestValue for InAppProduct {} +impl Resource for InAppProduct {} +impl ResponseResult for InAppProduct {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [images list edits](struct.EditImageListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ImagesListResponse { + /// no description provided + pub images: Vec, +} + +impl ResponseResult for ImagesListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [expansionfiles upload edits](struct.EditExpansionfileUploadCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ExpansionFilesUploadResponse { + /// no description provided + #[serde(alias="expansionFile")] + pub expansion_file: ExpansionFile, +} + +impl ResponseResult for ExpansionFilesUploadResponse {} + + +/// A SubscriptionDeferralInfo contains the data needed to defer a subscription purchase to a future expiry time. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct SubscriptionDeferralInfo { + /// The expected expiry time for the subscription. If the current expiry time for the subscription is not the value specified here, the deferral will not occur. + #[serde(alias="expectedExpiryTimeMillis")] + pub expected_expiry_time_millis: String, + /// The desired next expiry time for the subscription in milliseconds since Epoch. The given time must be after the current expiry time for the subscription. + #[serde(alias="desiredExpiryTimeMillis")] + pub desired_expiry_time_millis: String, +} + +impl Part for SubscriptionDeferralInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [listings update edits](struct.EditListingUpdateCall.html) (request|response) +/// * [listings patch edits](struct.EditListingPatchCall.html) (request|response) +/// * [listings get edits](struct.EditListingGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Listing { + /// URL of a promotional YouTube video for the app. + pub video: Option, + /// Short description of the app (previously known as promo text); this may be up to 80 characters in length. + #[serde(alias="shortDescription")] + pub short_description: Option, + /// Full description of the app; this may be up to 4000 characters in length. + #[serde(alias="fullDescription")] + pub full_description: Option, + /// Language localization code (for example, "de-AT" for Austrian German). + pub language: Option, + /// App's localized title. + pub title: Option, +} + +impl RequestValue for Listing {} +impl ResponseResult for Listing {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [batch inappproducts](struct.InappproductBatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InappproductsBatchRequest { + /// no description provided + pub entrys: Option>, +} + +impl RequestValue for InappproductsBatchRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MonthDay { + /// Day of a month, value in [1, 31] range. Valid range depends on the specified month. + pub day: u32, + /// Month of a year. e.g. 1 = JAN, 2 = FEB etc. + pub month: u32, +} + +impl Part for MonthDay {} + + +/// A ProductPurchase resource indicates the status of a user's inapp product purchase. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [products get purchases](struct.PurchaseProductGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductPurchase { + /// The consumption state of the inapp product. Possible values are: + /// - Yet to be consumed + /// - Consumed + #[serde(alias="consumptionState")] + pub consumption_state: i32, + /// A developer-specified string that contains supplemental information about an order. + #[serde(alias="developerPayload")] + pub developer_payload: String, + /// This kind represents an inappPurchase object in the androidpublisher service. + pub kind: String, + /// The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970). + #[serde(alias="purchaseTimeMillis")] + pub purchase_time_millis: String, + /// The purchase state of the order. Possible values are: + /// - Purchased + /// - Cancelled + #[serde(alias="purchaseState")] + pub purchase_state: i32, +} + +impl ResponseResult for ProductPurchase {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apklistings list edits](struct.EditApklistingListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ApkListingsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#apkListingsListResponse". + pub kind: String, + /// no description provided + pub listings: Vec, +} + +impl ResponseResult for ApkListingsListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [images deleteall edits](struct.EditImageDeleteallCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ImagesDeleteAllResponse { + /// no description provided + pub deleted: Vec, +} + +impl ResponseResult for ImagesDeleteAllResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [tracks update edits](struct.EditTrackUpdateCall.html) (request|response) +/// * [tracks patch edits](struct.EditTrackPatchCall.html) (request|response) +/// * [tracks get edits](struct.EditTrackGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Track { + /// no description provided + pub track: Option, + /// no description provided + #[serde(alias="userFraction")] + pub user_fraction: Option, + /// no description provided + #[serde(alias="versionCodes")] + pub version_codes: Option>, +} + +impl RequestValue for Track {} +impl ResponseResult for Track {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Season { + /// Inclusive start date of the recurrence period. + pub start: MonthDay, + /// Inclusive end date of the recurrence period. + pub end: MonthDay, +} + +impl Part for Season {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InAppProductListing { + /// no description provided + pub description: String, + /// no description provided + pub title: String, +} + +impl Part for InAppProductListing {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [subscriptions defer purchases](struct.PurchaseSubscriptionDeferCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct SubscriptionPurchasesDeferRequest { + /// The information about the new desired expiry time for the subscription. + #[serde(alias="deferralInfo")] + pub deferral_info: Option, +} + +impl RequestValue for SubscriptionPurchasesDeferRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InappproductsInsertResponse { + /// no description provided + pub inappproduct: InAppProduct, +} + +impl Part for InappproductsInsertResponse {} + + +/// Defines an APK available for this application that is hosted externally and not uploaded to Google Play. This function is only available to enterprises who are using Android for Work, and whos application is restricted to the enterprise private channel +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExternallyHostedApk { + /// The icon image from the APK, as a base64 encoded byte array. + #[serde(alias="iconBase64")] + pub icon_base64: String, + /// A certificate (or array of certificates if a certificate-chain is used) used to signed this APK, represented as a base64 encoded byte array. + #[serde(alias="certificateBase64s")] + pub certificate_base64s: Vec, + /// The URL at which the APK is hosted. This must be an https URL. + #[serde(alias="externallyHostedUrl")] + pub externally_hosted_url: String, + /// The maximum SDK supported by this APK (optional). + #[serde(alias="maximumSdk")] + pub maximum_sdk: i32, + /// The SHA256 checksum of this APK, represented as a base64 encoded byte array. + #[serde(alias="fileSha256Base64")] + pub file_sha256_base64: String, + /// The permissions requested by this APK. + #[serde(alias="usesPermissions")] + pub uses_permissions: Vec, + /// The SHA1 checksum of this APK, represented as a base64 encoded byte array. + #[serde(alias="fileSha1Base64")] + pub file_sha1_base64: String, + /// The features required by this APK (optional). + #[serde(alias="usesFeatures")] + pub uses_features: Vec, + /// The native code environments supported by this APK (optional). + #[serde(alias="nativeCodes")] + pub native_codes: Vec, + /// The file size in bytes of this APK. + #[serde(alias="fileSize")] + pub file_size: String, + /// The version name of this APK. + #[serde(alias="versionName")] + pub version_name: String, + /// The version code of this APK. + #[serde(alias="versionCode")] + pub version_code: i32, + /// The minimum SDK targeted by this APK. + #[serde(alias="minimumSdk")] + pub minimum_sdk: i32, + /// The application label. + #[serde(alias="applicationLabel")] + pub application_label: String, + /// The package name. + #[serde(alias="packageName")] + pub package_name: String, +} + +impl Part for ExternallyHostedApk {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [details patch edits](struct.EditDetailPatchCall.html) (request|response) +/// * [details update edits](struct.EditDetailUpdateCall.html) (request|response) +/// * [details get edits](struct.EditDetailGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AppDetails { + /// The user-visible support email for this app. + #[serde(alias="contactEmail")] + pub contact_email: Option, + /// The user-visible support telephone number for this app. + #[serde(alias="contactPhone")] + pub contact_phone: Option, + /// The user-visible website for this app. + #[serde(alias="contactWebsite")] + pub contact_website: Option, + /// Default language code, in BCP 47 format (eg "en-US"). + #[serde(alias="defaultLanguage")] + pub default_language: Option, +} + +impl RequestValue for AppDetails {} +impl ResponseResult for AppDetails {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InappproductsBatchResponseEntry { + /// no description provided + #[serde(alias="batchId")] + pub batch_id: u32, + /// no description provided + pub inappproductsinsertresponse: InappproductsInsertResponse, + /// no description provided + pub inappproductsupdateresponse: InappproductsUpdateResponse, +} + +impl Part for InappproductsBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InappproductsInsertRequest { + /// no description provided + pub inappproduct: InAppProduct, +} + +impl Part for InappproductsInsertRequest {} + + +/// A permission used by this APK. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExternallyHostedApkUsesPermission { + /// Optionally, the maximum SDK version for which the permission is required. + #[serde(alias="maxSdkVersion")] + pub max_sdk_version: i32, + /// The name of the permission requested. + pub name: String, +} + +impl Part for ExternallyHostedApkUsesPermission {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InappproductsBatchRequestEntry { + /// no description provided + #[serde(alias="batchId")] + pub batch_id: u32, + /// no description provided + pub inappproductsinsertrequest: InappproductsInsertRequest, + /// no description provided + #[serde(alias="methodName")] + pub method_name: String, + /// no description provided + pub inappproductsupdaterequest: InappproductsUpdateRequest, +} + +impl Part for InappproductsBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [tracks list edits](struct.EditTrackListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TracksListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#tracksListResponse". + pub kind: String, + /// no description provided + pub tracks: Vec, +} + +impl ResponseResult for TracksListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [subscriptions defer purchases](struct.PurchaseSubscriptionDeferCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SubscriptionPurchasesDeferResponse { + /// The new expiry time for the subscription in milliseconds since the Epoch. + #[serde(alias="newExpiryTimeMillis")] + pub new_expiry_time_millis: String, +} + +impl ResponseResult for SubscriptionPurchasesDeferResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list inappproducts](struct.InappproductListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InappproductsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#inappproductsListResponse". + pub kind: String, + /// no description provided + #[serde(alias="tokenPagination")] + pub token_pagination: TokenPagination, + /// no description provided + #[serde(alias="pageInfo")] + pub page_info: PageInfo, + /// no description provided + pub inappproduct: Vec, +} + +impl ResponseResult for InappproductsListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TokenPagination { + /// no description provided + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// no description provided + #[serde(alias="previousPageToken")] + pub previous_page_token: String, +} + +impl Part for TokenPagination {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apklistings get edits](struct.EditApklistingGetCall.html) (response) +/// * [apklistings patch edits](struct.EditApklistingPatchCall.html) (request|response) +/// * [apklistings update edits](struct.EditApklistingUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ApkListing { + /// Describe what's new in your APK. + #[serde(alias="recentChanges")] + pub recent_changes: Option, + /// The language code, in BCP 47 format (eg "en-US"). + pub language: Option, +} + +impl RequestValue for ApkListing {} +impl ResponseResult for ApkListing {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [testers get edits](struct.EditTesterGetCall.html) (response) +/// * [testers patch edits](struct.EditTesterPatchCall.html) (request|response) +/// * [testers update edits](struct.EditTesterUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Testers { + /// no description provided + #[serde(alias="googleGroups")] + pub google_groups: Option>, + /// no description provided + #[serde(alias="googlePlusCommunities")] + pub google_plus_communities: Option>, +} + +impl RequestValue for Testers {} +impl ResponseResult for Testers {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [expansionfiles get edits](struct.EditExpansionfileGetCall.html) (response) +/// * [expansionfiles patch edits](struct.EditExpansionfilePatchCall.html) (request|response) +/// * [expansionfiles update edits](struct.EditExpansionfileUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExpansionFile { + /// If set this APK's Expansion File references another APK's Expansion File. The file_size field will not be set. + #[serde(alias="referencesVersion")] + pub references_version: Option, + /// If set this field indicates that this APK has an Expansion File uploaded to it: this APK does not reference another APK's Expansion File. The field's value is the size of the uploaded Expansion File in bytes. + #[serde(alias="fileSize")] + pub file_size: Option, +} + +impl RequestValue for ExpansionFile {} +impl ResponseResult for ExpansionFile {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apks addexternallyhosted edits](struct.EditApkAddexternallyhostedCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ApksAddExternallyHostedResponse { + /// The definition of the externally-hosted APK and where it is located. + #[serde(alias="externallyHostedApk")] + pub externally_hosted_apk: ExternallyHostedApk, +} + +impl ResponseResult for ApksAddExternallyHostedResponse {} + + +/// A SubscriptionPurchase resource indicates the status of a user's subscription purchase. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [subscriptions get purchases](struct.PurchaseSubscriptionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SubscriptionPurchase { + /// Whether the subscription will automatically be renewed when it reaches its current expiry time. + #[serde(alias="autoRenewing")] + pub auto_renewing: bool, + /// This kind represents a subscriptionPurchase object in the androidpublisher service. + pub kind: String, + /// Time at which the subscription will expire, in milliseconds since Epoch. + #[serde(alias="expiryTimeMillis")] + pub expiry_time_millis: String, + /// Time at which the subscription was granted, in milliseconds since Epoch. + #[serde(alias="startTimeMillis")] + pub start_time_millis: String, +} + +impl ResponseResult for SubscriptionPurchase {} + + +/// Represents an edit of an app. An edit allows clients to make multiple changes before committing them in one operation. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert edits](struct.EditInsertCall.html) (request|response) +/// * [commit edits](struct.EditCommitCall.html) (response) +/// * [validate edits](struct.EditValidateCall.html) (response) +/// * [get edits](struct.EditGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AppEdit { + /// The time at which the edit will expire and will be no longer valid for use in any subsequent API calls (encoded as seconds since the Epoch). + #[serde(alias="expiryTimeSeconds")] + pub expiry_time_seconds: Option, + /// The ID of the edit that can be used in subsequent API calls. + pub id: Option, +} + +impl RequestValue for AppEdit {} +impl ResponseResult for AppEdit {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apks list edits](struct.EditApkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ApksListResponse { + /// no description provided + pub apks: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#apksListResponse". + pub kind: String, +} + +impl ResponseResult for ApksListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InappproductsUpdateRequest { + /// no description provided + pub inappproduct: InAppProduct, +} + +impl Part for InappproductsUpdateRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PageInfo { + /// no description provided + #[serde(alias="resultPerPage")] + pub result_per_page: i32, + /// no description provided + #[serde(alias="startIndex")] + pub start_index: i32, + /// no description provided + #[serde(alias="totalResults")] + pub total_results: i32, +} + +impl Part for PageInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [images upload edits](struct.EditImageUploadCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ImagesUploadResponse { + /// no description provided + pub image: Image, +} + +impl ResponseResult for ImagesUploadResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apks upload edits](struct.EditApkUploadCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Apk { + /// The version code of the APK, as specified in the APK's manifest file. + #[serde(alias="versionCode")] + pub version_code: i32, + /// Information about the binary payload of this APK. + pub binary: ApkBinary, +} + +impl ResponseResult for Apk {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [batch inappproducts](struct.InappproductBatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InappproductsBatchResponse { + /// no description provided + pub entrys: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#inappproductsBatchResponse". + pub kind: String, +} + +impl ResponseResult for InappproductsBatchResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Image { + /// A URL that will serve a preview of the image. + pub url: String, + /// A sha1 hash of the image that was uploaded. + pub sha1: String, + /// A unique id representing this image. + pub id: String, +} + +impl Part for Image {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [apks addexternallyhosted edits](struct.EditApkAddexternallyhostedCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ApksAddExternallyHostedRequest { + /// The definition of the externally-hosted APK and where it is located. + #[serde(alias="externallyHostedApk")] + pub externally_hosted_apk: Option, +} + +impl RequestValue for ApksAddExternallyHostedRequest {} + + +/// Represents the binary payload of an APK. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ApkBinary { + /// A sha1 hash of the APK payload, encoded as a hex string and matching the output of the sha1sum command. + pub sha1: String, +} + +impl Part for ApkBinary {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Price { + /// 3 letter Currency code, as defined by ISO 4217. + pub currency: String, + /// The price in millionths of the currency base unit represented as a string. + #[serde(alias="priceMicros")] + pub price_micros: String, +} + +impl Part for Price {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [listings list edits](struct.EditListingListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListingsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidpublisher#listingsListResponse". + pub kind: String, + /// no description provided + pub listings: Vec, +} + +impl ResponseResult for ListingsListResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *purchase* resources. +/// It is not used directly, but through the `AndroidPublisher` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidpublisher2" as androidpublisher2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidpublisher2::AndroidPublisher; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `products_get(...)`, `subscriptions_cancel(...)`, `subscriptions_defer(...)`, `subscriptions_get(...)`, `subscriptions_refund(...)` and `subscriptions_revoke(...)` +/// // to build up your call. +/// let rb = hub.purchases(); +/// # } +/// ``` +pub struct PurchaseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PurchaseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Refunds and immediately revokes a user's subscription purchase. Access to the subscription will be terminated immediately and it will stop recurring. + pub fn subscriptions_revoke(&self, package_name: &str, subscription_id: &str, token: &str) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> { + PurchaseSubscriptionRevokeCall { + hub: self.hub, + _package_name: package_name.to_string(), + _subscription_id: subscription_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Checks the purchase and consumption status of an inapp item. + pub fn products_get(&self, package_name: &str, product_id: &str, token: &str) -> PurchaseProductGetCall<'a, C, NC, A> { + PurchaseProductGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _product_id: product_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Checks whether a user's subscription purchase is valid and returns its expiry time. + pub fn subscriptions_get(&self, package_name: &str, subscription_id: &str, token: &str) -> PurchaseSubscriptionGetCall<'a, C, NC, A> { + PurchaseSubscriptionGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _subscription_id: subscription_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels a user's subscription purchase. The subscription remains valid until its expiration time. + pub fn subscriptions_cancel(&self, package_name: &str, subscription_id: &str, token: &str) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> { + PurchaseSubscriptionCancelCall { + hub: self.hub, + _package_name: package_name.to_string(), + _subscription_id: subscription_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Refunds a user's subscription purchase, but the subscription remains valid until its expiration time and it will continue to recur. + pub fn subscriptions_refund(&self, package_name: &str, subscription_id: &str, token: &str) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> { + PurchaseSubscriptionRefundCall { + hub: self.hub, + _package_name: package_name.to_string(), + _subscription_id: subscription_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Defers a user's subscription purchase until a specified future expiration time. + pub fn subscriptions_defer(&self, request: &SubscriptionPurchasesDeferRequest, package_name: &str, subscription_id: &str, token: &str) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + PurchaseSubscriptionDeferCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _subscription_id: subscription_id.to_string(), + _token: token.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *edit* resources. +/// It is not used directly, but through the `AndroidPublisher` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidpublisher2" as androidpublisher2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidpublisher2::AndroidPublisher; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `apklistings_delete(...)`, `apklistings_deleteall(...)`, `apklistings_get(...)`, `apklistings_list(...)`, `apklistings_patch(...)`, `apklistings_update(...)`, `apks_addexternallyhosted(...)`, `apks_list(...)`, `apks_upload(...)`, `commit(...)`, `delete(...)`, `details_get(...)`, `details_patch(...)`, `details_update(...)`, `expansionfiles_get(...)`, `expansionfiles_patch(...)`, `expansionfiles_update(...)`, `expansionfiles_upload(...)`, `get(...)`, `images_delete(...)`, `images_deleteall(...)`, `images_list(...)`, `images_upload(...)`, `insert(...)`, `listings_delete(...)`, `listings_deleteall(...)`, `listings_get(...)`, `listings_list(...)`, `listings_patch(...)`, `listings_update(...)`, `testers_get(...)`, `testers_patch(...)`, `testers_update(...)`, `tracks_get(...)`, `tracks_list(...)`, `tracks_patch(...)`, `tracks_update(...)` and `validate(...)` +/// // to build up your call. +/// let rb = hub.edits(); +/// # } +/// ``` +pub struct EditMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for EditMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Uploads a new image and adds it to the list of images for the specified language and image type. + pub fn images_upload(&self, package_name: &str, edit_id: &str, language: &str, image_type: &str) -> EditImageUploadCall<'a, C, NC, A> { + EditImageUploadCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _image_type: image_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the APK's Expansion File configuration to reference another APK's Expansion Files. To add a new Expansion File use the Upload method. + pub fn expansionfiles_update(&self, request: &ExpansionFile, package_name: &str, edit_id: &str, apk_version_code: i32, expansion_file_type: &str) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + EditExpansionfileUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _expansion_file_type: expansion_file_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches app details for this edit. This includes the default language and developer support contact information. + pub fn details_get(&self, package_name: &str, edit_id: &str) -> EditDetailGetCall<'a, C, NC, A> { + EditDetailGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the APK-specific localized listing for a specified APK and language code. + pub fn apklistings_delete(&self, package_name: &str, edit_id: &str, apk_version_code: i32, language: &str) -> EditApklistingDeleteCall<'a, C, NC, A> { + EditApklistingDeleteCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes all localized listings from an edit. + pub fn listings_deleteall(&self, package_name: &str, edit_id: &str) -> EditListingDeleteallCall<'a, C, NC, A> { + EditListingDeleteallCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new APK without uploading the APK itself to Google Play, instead hosting the APK at a specified URL. This function is only available to enterprises using Google Play for work whose application is configured to restrict distribution to the enterprise domain. + pub fn apks_addexternallyhosted(&self, request: &ApksAddExternallyHostedRequest, package_name: &str, edit_id: &str) -> EditApkAddexternallyhostedCall<'a, C, NC, A> { + EditApkAddexternallyhostedCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes all the APK-specific localized listings for a specified APK. + pub fn apklistings_deleteall(&self, package_name: &str, edit_id: &str, apk_version_code: i32) -> EditApklistingDeleteallCall<'a, C, NC, A> { + EditApklistingDeleteallCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates app details for this edit. + pub fn details_update(&self, request: &AppDetails, package_name: &str, edit_id: &str) -> EditDetailUpdateCall<'a, C, NC, A> { + EditDetailUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches the track configuration for the specified track type. Includes the APK version codes that are in this track. + pub fn tracks_get(&self, package_name: &str, edit_id: &str, track: &str) -> EditTrackGetCall<'a, C, NC, A> { + EditTrackGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the APK's Expansion File configuration to reference another APK's Expansion Files. To add a new Expansion File use the Upload method. This method supports patch semantics. + pub fn expansionfiles_patch(&self, request: &ExpansionFile, package_name: &str, edit_id: &str, apk_version_code: i32, expansion_file_type: &str) -> EditExpansionfilePatchCall<'a, C, NC, A> { + EditExpansionfilePatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _expansion_file_type: expansion_file_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all images for the specified language and image type. + pub fn images_list(&self, package_name: &str, edit_id: &str, language: &str, image_type: &str) -> EditImageListCall<'a, C, NC, A> { + EditImageListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _image_type: image_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the track configuration for the specified track type. When halted, the rollout track cannot be updated without adding new APKs, and adding new APKs will cause it to resume. + pub fn tracks_update(&self, request: &Track, package_name: &str, edit_id: &str, track: &str) -> EditTrackUpdateCall<'a, C, NC, A> { + EditTrackUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates or updates a localized store listing. This method supports patch semantics. + pub fn listings_patch(&self, request: &Listing, package_name: &str, edit_id: &str, language: &str) -> EditListingPatchCall<'a, C, NC, A> { + EditListingPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns information about the edit specified. Calls will fail if the edit is no long active (e.g. has been deleted, superseded or expired). + pub fn get(&self, package_name: &str, edit_id: &str) -> EditGetCall<'a, C, NC, A> { + EditGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the image (specified by id) from the edit. + pub fn images_delete(&self, package_name: &str, edit_id: &str, language: &str, image_type: &str, image_id: &str) -> EditImageDeleteCall<'a, C, NC, A> { + EditImageDeleteCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _image_type: image_type.to_string(), + _image_id: image_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn apks_upload(&self, package_name: &str, edit_id: &str) -> EditApkUploadCall<'a, C, NC, A> { + EditApkUploadCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates or creates the APK-specific localized listing for a specified APK and language code. + pub fn apklistings_update(&self, request: &ApkListing, package_name: &str, edit_id: &str, apk_version_code: i32, language: &str) -> EditApklistingUpdateCall<'a, C, NC, A> { + EditApklistingUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn apks_list(&self, package_name: &str, edit_id: &str) -> EditApkListCall<'a, C, NC, A> { + EditApkListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates or creates the APK-specific localized listing for a specified APK and language code. This method supports patch semantics. + pub fn apklistings_patch(&self, request: &ApkListing, package_name: &str, edit_id: &str, apk_version_code: i32, language: &str) -> EditApklistingPatchCall<'a, C, NC, A> { + EditApklistingPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches information about a localized store listing. + pub fn listings_get(&self, package_name: &str, edit_id: &str, language: &str) -> EditListingGetCall<'a, C, NC, A> { + EditListingGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn testers_get(&self, package_name: &str, edit_id: &str, track: &str) -> EditTesterGetCall<'a, C, NC, A> { + EditTesterGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an edit for an app. Creating a new edit will automatically delete any of your previous edits so this method need only be called if you want to preemptively abandon an edit. + pub fn delete(&self, package_name: &str, edit_id: &str) -> EditDeleteCall<'a, C, NC, A> { + EditDeleteCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Uploads and attaches a new Expansion File to the APK specified. + pub fn expansionfiles_upload(&self, package_name: &str, edit_id: &str, apk_version_code: i32, expansion_file_type: &str) -> EditExpansionfileUploadCall<'a, C, NC, A> { + EditExpansionfileUploadCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _expansion_file_type: expansion_file_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new edit for an app, populated with the app's current state. + pub fn insert(&self, request: &AppEdit, package_name: &str) -> EditInsertCall<'a, C, NC, A> { + EditInsertCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns all of the localized store listings attached to this edit. + pub fn listings_list(&self, package_name: &str, edit_id: &str) -> EditListingListCall<'a, C, NC, A> { + EditListingListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn testers_patch(&self, request: &Testers, package_name: &str, edit_id: &str, track: &str) -> EditTesterPatchCall<'a, C, NC, A> { + EditTesterPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Commits/applies the changes made in this edit back to the app. + pub fn commit(&self, package_name: &str, edit_id: &str) -> EditCommitCall<'a, C, NC, A> { + EditCommitCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all the track configurations for this edit. + pub fn tracks_list(&self, package_name: &str, edit_id: &str) -> EditTrackListCall<'a, C, NC, A> { + EditTrackListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Checks that the edit can be successfully committed. The edit's changes are not applied to the live app. + pub fn validate(&self, package_name: &str, edit_id: &str) -> EditValidateCall<'a, C, NC, A> { + EditValidateCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates or updates a localized store listing. + pub fn listings_update(&self, request: &Listing, package_name: &str, edit_id: &str, language: &str) -> EditListingUpdateCall<'a, C, NC, A> { + EditListingUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches the Expansion File configuration for the APK specified. + pub fn expansionfiles_get(&self, package_name: &str, edit_id: &str, apk_version_code: i32, expansion_file_type: &str) -> EditExpansionfileGetCall<'a, C, NC, A> { + EditExpansionfileGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _expansion_file_type: expansion_file_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes all images for the specified language and image type. + pub fn images_deleteall(&self, package_name: &str, edit_id: &str, language: &str, image_type: &str) -> EditImageDeleteallCall<'a, C, NC, A> { + EditImageDeleteallCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _image_type: image_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates app details for this edit. This method supports patch semantics. + pub fn details_patch(&self, request: &AppDetails, package_name: &str, edit_id: &str) -> EditDetailPatchCall<'a, C, NC, A> { + EditDetailPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the track configuration for the specified track type. When halted, the rollout track cannot be updated without adding new APKs, and adding new APKs will cause it to resume. This method supports patch semantics. + pub fn tracks_patch(&self, request: &Track, package_name: &str, edit_id: &str, track: &str) -> EditTrackPatchCall<'a, C, NC, A> { + EditTrackPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified localized store listing from an edit. + pub fn listings_delete(&self, package_name: &str, edit_id: &str, language: &str) -> EditListingDeleteCall<'a, C, NC, A> { + EditListingDeleteCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches the APK-specific localized listing for a specified APK and language code. + pub fn apklistings_get(&self, package_name: &str, edit_id: &str, apk_version_code: i32, language: &str) -> EditApklistingGetCall<'a, C, NC, A> { + EditApklistingGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _language: language.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn testers_update(&self, request: &Testers, package_name: &str, edit_id: &str, track: &str) -> EditTesterUpdateCall<'a, C, NC, A> { + EditTesterUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _track: track.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all the APK-specific localized listings for a specified APK. + pub fn apklistings_list(&self, package_name: &str, edit_id: &str, apk_version_code: i32) -> EditApklistingListCall<'a, C, NC, A> { + EditApklistingListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _edit_id: edit_id.to_string(), + _apk_version_code: apk_version_code, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *inappproduct* resources. +/// It is not used directly, but through the `AndroidPublisher` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-androidpublisher2" as androidpublisher2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use androidpublisher2::AndroidPublisher; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `batch(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.inappproducts(); +/// # } +/// ``` +pub struct InappproductMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for InappproductMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductMethods<'a, C, NC, A> { + + pub fn batch(&self, request: &InappproductsBatchRequest) -> InappproductBatchCall<'a, C, NC, A> { + InappproductBatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List all the in-app products for an Android app, both subscriptions and managed in-app products.. + pub fn list(&self, package_name: &str) -> InappproductListCall<'a, C, NC, A> { + InappproductListCall { + hub: self.hub, + _package_name: package_name.to_string(), + _token: Default::default(), + _start_index: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new in-app product for an app. + pub fn insert(&self, request: &InAppProduct, package_name: &str) -> InappproductInsertCall<'a, C, NC, A> { + InappproductInsertCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _auto_convert_missing_prices: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete an in-app product for an app. + pub fn delete(&self, package_name: &str, sku: &str) -> InappproductDeleteCall<'a, C, NC, A> { + InappproductDeleteCall { + hub: self.hub, + _package_name: package_name.to_string(), + _sku: sku.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns information about the in-app product specified. + pub fn get(&self, package_name: &str, sku: &str) -> InappproductGetCall<'a, C, NC, A> { + InappproductGetCall { + hub: self.hub, + _package_name: package_name.to_string(), + _sku: sku.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the details of an in-app product. + pub fn update(&self, request: &InAppProduct, package_name: &str, sku: &str) -> InappproductUpdateCall<'a, C, NC, A> { + InappproductUpdateCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _sku: sku.to_string(), + _auto_convert_missing_prices: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the details of an in-app product. This method supports patch semantics. + pub fn patch(&self, request: &InAppProduct, package_name: &str, sku: &str) -> InappproductPatchCall<'a, C, NC, A> { + InappproductPatchCall { + hub: self.hub, + _request: request.clone(), + _package_name: package_name.to_string(), + _sku: sku.to_string(), + _auto_convert_missing_prices: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Refunds and immediately revokes a user's subscription purchase. Access to the subscription will be terminated immediately and it will stop recurring. +/// +/// A builder for the *subscriptions.revoke* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().subscriptions_revoke("packageName", "subscriptionId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseSubscriptionRevokeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _subscription_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseSubscriptionRevokeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseSubscriptionRevokeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.subscriptions.revoke", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("subscriptionId", self._subscription_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["packageName", "subscriptionId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:revoke".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{subscriptionId}", "subscriptionId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "subscriptionId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *subscription id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The purchased subscription ID (for example, 'monthly001'). + pub fn subscription_id(mut self, new_value: &str) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> { + self._subscription_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the subscription was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseSubscriptionRevokeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Checks the purchase and consumption status of an inapp item. +/// +/// A builder for the *products.get* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().products_get("packageName", "productId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseProductGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _product_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseProductGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseProductGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductPurchase)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.products.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("productId", self._product_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "packageName", "productId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/products/{productId}/tokens/{token}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{productId}", "productId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "productId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application the inapp product was sold in (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseProductGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The inapp product SKU (for example, 'com.some.thing.inapp1'). + pub fn product_id(mut self, new_value: &str) -> PurchaseProductGetCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the inapp product was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseProductGetCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseProductGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseProductGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseProductGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Checks whether a user's subscription purchase is valid and returns its expiry time. +/// +/// A builder for the *subscriptions.get* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().subscriptions_get("packageName", "subscriptionId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseSubscriptionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _subscription_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseSubscriptionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseSubscriptionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SubscriptionPurchase)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.subscriptions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("subscriptionId", self._subscription_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "packageName", "subscriptionId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{subscriptionId}", "subscriptionId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "subscriptionId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseSubscriptionGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *subscription id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The purchased subscription ID (for example, 'monthly001'). + pub fn subscription_id(mut self, new_value: &str) -> PurchaseSubscriptionGetCall<'a, C, NC, A> { + self._subscription_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the subscription was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseSubscriptionGetCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseSubscriptionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseSubscriptionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseSubscriptionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Cancels a user's subscription purchase. The subscription remains valid until its expiration time. +/// +/// A builder for the *subscriptions.cancel* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().subscriptions_cancel("packageName", "subscriptionId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseSubscriptionCancelCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _subscription_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseSubscriptionCancelCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseSubscriptionCancelCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.subscriptions.cancel", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("subscriptionId", self._subscription_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["packageName", "subscriptionId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:cancel".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{subscriptionId}", "subscriptionId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "subscriptionId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *subscription id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The purchased subscription ID (for example, 'monthly001'). + pub fn subscription_id(mut self, new_value: &str) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> { + self._subscription_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the subscription was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseSubscriptionCancelCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Refunds a user's subscription purchase, but the subscription remains valid until its expiration time and it will continue to recur. +/// +/// A builder for the *subscriptions.refund* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().subscriptions_refund("packageName", "subscriptionId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseSubscriptionRefundCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _subscription_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseSubscriptionRefundCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseSubscriptionRefundCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.subscriptions.refund", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("subscriptionId", self._subscription_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["packageName", "subscriptionId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:refund".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{subscriptionId}", "subscriptionId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "subscriptionId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *subscription id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The purchased subscription ID (for example, 'monthly001'). + pub fn subscription_id(mut self, new_value: &str) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> { + self._subscription_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the subscription was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseSubscriptionRefundCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Defers a user's subscription purchase until a specified future expiration time. +/// +/// A builder for the *subscriptions.defer* method supported by a *purchase* resource. +/// It is not used directly, but through a `PurchaseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::SubscriptionPurchasesDeferRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: SubscriptionPurchasesDeferRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.purchases().subscriptions_defer(&req, "packageName", "subscriptionId", "token") +/// .doit(); +/// # } +/// ``` +pub struct PurchaseSubscriptionDeferCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: SubscriptionPurchasesDeferRequest, + _package_name: String, + _subscription_id: String, + _token: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PurchaseSubscriptionDeferCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PurchaseSubscriptionDeferCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SubscriptionPurchasesDeferResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.purchases.subscriptions.defer", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("subscriptionId", self._subscription_id.to_string())); + params.push(("token", self._token.to_string())); + for &field in ["alt", "packageName", "subscriptionId", "token"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:defer".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{subscriptionId}", "subscriptionId"), ("{token}", "token")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "subscriptionId", "token"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &SubscriptionPurchasesDeferRequest) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). + pub fn package_name(mut self, new_value: &str) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *subscription id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The purchased subscription ID (for example, 'monthly001'). + pub fn subscription_id(mut self, new_value: &str) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + self._subscription_id = new_value.to_string(); + self + } + /// Sets the *token* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The token provided to the user's device when the subscription was purchased. + pub fn token(mut self, new_value: &str) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + self._token = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PurchaseSubscriptionDeferCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Uploads a new image and adds it to the list of images for the specified language and image type. +/// +/// A builder for the *images.upload* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().images_upload("packageName", "editId", "language", "imageType") +/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct EditImageUploadCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _image_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditImageUploadCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditImageUploadCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, ImagesUploadResponse)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.images.upload", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + params.push(("imageType", self._image_type.to_string())); + for &field in ["alt", "packageName", "editId", "language", "imageType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language"), ("{imageType}", "imageType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "language", "imageType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + if protocol == "simple" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + req = req.header(ContentType(reader_mime_type.clone())) + .header(ContentLength(size)) + .body(&mut reader); + } + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 15MB + /// * *multipart*: yes + /// * *valid mime types*: 'image/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, ImagesUploadResponse)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 15MB + /// * *multipart*: yes + /// * *valid mime types*: 'image/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, ImagesUploadResponse)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditImageUploadCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditImageUploadCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing whose images are to read or modified. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditImageUploadCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *image type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn image_type(mut self, new_value: &str) -> EditImageUploadCall<'a, C, NC, A> { + self._image_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditImageUploadCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditImageUploadCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditImageUploadCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the APK's Expansion File configuration to reference another APK's Expansion Files. To add a new Expansion File use the Upload method. +/// +/// A builder for the *expansionfiles.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::ExpansionFile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ExpansionFile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().expansionfiles_update(&req, "packageName", "editId", -75, "expansionFileType") +/// .doit(); +/// # } +/// ``` +pub struct EditExpansionfileUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: ExpansionFile, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _expansion_file_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditExpansionfileUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditExpansionfileUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ExpansionFile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.expansionfiles.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("expansionFileType", self._expansion_file_type.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{expansionFileType}", "expansionFileType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ExpansionFile) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The version code of the APK whose Expansion File configuration is being read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *expansion file type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn expansion_file_type(mut self, new_value: &str) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._expansion_file_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditExpansionfileUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditExpansionfileUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditExpansionfileUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetches app details for this edit. This includes the default language and developer support contact information. +/// +/// A builder for the *details.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().details_get("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditDetailGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditDetailGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditDetailGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppDetails)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.details.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/details".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditDetailGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditDetailGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditDetailGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditDetailGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditDetailGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the APK-specific localized listing for a specified APK and language code. +/// +/// A builder for the *apklistings.delete* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_delete("packageName", "editId", -97, "language") +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["packageName", "editId", "apkVersionCode", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingDeleteCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingDeleteCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingDeleteCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the APK-specific localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditApklistingDeleteCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes all localized listings from an edit. +/// +/// A builder for the *listings.deleteall* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_deleteall("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditListingDeleteallCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingDeleteallCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingDeleteallCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.deleteall", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingDeleteallCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingDeleteallCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingDeleteallCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingDeleteallCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingDeleteallCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new APK without uploading the APK itself to Google Play, instead hosting the APK at a specified URL. This function is only available to enterprises using Google Play for work whose application is configured to restrict distribution to the enterprise domain. +/// +/// A builder for the *apks.addexternallyhosted* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::ApksAddExternallyHostedRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ApksAddExternallyHostedRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apks_addexternallyhosted(&req, "packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditApkAddexternallyhostedCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: ApksAddExternallyHostedRequest, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApkAddexternallyhostedCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApkAddexternallyhostedCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApksAddExternallyHostedResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apks.addexternallyhosted", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/externallyHosted".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ApksAddExternallyHostedRequest) -> EditApkAddexternallyhostedCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApkAddexternallyhostedCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApkAddexternallyhostedCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApkAddexternallyhostedCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApkAddexternallyhostedCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApkAddexternallyhostedCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes all the APK-specific localized listings for a specified APK. +/// +/// A builder for the *apklistings.deleteall* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_deleteall("packageName", "editId", -56) +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingDeleteallCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingDeleteallCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingDeleteallCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.deleteall", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + for &field in ["packageName", "editId", "apkVersionCode"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "apkVersionCode"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingDeleteallCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingDeleteallCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingDeleteallCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingDeleteallCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingDeleteallCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingDeleteallCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates app details for this edit. +/// +/// A builder for the *details.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::AppDetails; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AppDetails = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().details_update(&req, "packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditDetailUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: AppDetails, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditDetailUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditDetailUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppDetails)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.details.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/details".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AppDetails) -> EditDetailUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditDetailUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditDetailUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditDetailUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditDetailUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditDetailUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetches the track configuration for the specified track type. Includes the APK version codes that are in this track. +/// +/// A builder for the *tracks.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().tracks_get("packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTrackGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTrackGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTrackGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Track)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.tracks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/tracks/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTrackGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTrackGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The track type to read or modify. + pub fn track(mut self, new_value: &str) -> EditTrackGetCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTrackGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTrackGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTrackGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the APK's Expansion File configuration to reference another APK's Expansion Files. To add a new Expansion File use the Upload method. This method supports patch semantics. +/// +/// A builder for the *expansionfiles.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::ExpansionFile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ExpansionFile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().expansionfiles_patch(&req, "packageName", "editId", -46, "expansionFileType") +/// .doit(); +/// # } +/// ``` +pub struct EditExpansionfilePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: ExpansionFile, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _expansion_file_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditExpansionfilePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditExpansionfilePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ExpansionFile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.expansionfiles.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("expansionFileType", self._expansion_file_type.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{expansionFileType}", "expansionFileType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ExpansionFile) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The version code of the APK whose Expansion File configuration is being read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *expansion file type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn expansion_file_type(mut self, new_value: &str) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._expansion_file_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditExpansionfilePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditExpansionfilePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditExpansionfilePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all images for the specified language and image type. +/// +/// A builder for the *images.list* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().images_list("packageName", "editId", "language", "imageType") +/// .doit(); +/// # } +/// ``` +pub struct EditImageListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _image_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditImageListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditImageListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ImagesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.images.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + params.push(("imageType", self._image_type.to_string())); + for &field in ["alt", "packageName", "editId", "language", "imageType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language"), ("{imageType}", "imageType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "language", "imageType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditImageListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditImageListCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing whose images are to read or modified. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditImageListCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *image type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn image_type(mut self, new_value: &str) -> EditImageListCall<'a, C, NC, A> { + self._image_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditImageListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditImageListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditImageListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the track configuration for the specified track type. When halted, the rollout track cannot be updated without adding new APKs, and adding new APKs will cause it to resume. +/// +/// A builder for the *tracks.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Track; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Track = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().tracks_update(&req, "packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTrackUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Track, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTrackUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTrackUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Track)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.tracks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/tracks/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Track) -> EditTrackUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTrackUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTrackUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The track type to read or modify. + pub fn track(mut self, new_value: &str) -> EditTrackUpdateCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTrackUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTrackUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTrackUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates or updates a localized store listing. This method supports patch semantics. +/// +/// A builder for the *listings.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Listing; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Listing = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_patch(&req, "packageName", "editId", "language") +/// .doit(); +/// # } +/// ``` +pub struct EditListingPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Listing, + _package_name: String, + _edit_id: String, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Listing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Listing) -> EditListingPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingPatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditListingPatchCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns information about the edit specified. Calls will fail if the edit is no long active (e.g. has been deleted, superseded or expired). +/// +/// A builder for the *get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().get("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppEdit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the image (specified by id) from the edit. +/// +/// A builder for the *images.delete* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().images_delete("packageName", "editId", "language", "imageType", "imageId") +/// .doit(); +/// # } +/// ``` +pub struct EditImageDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _image_type: String, + _image_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditImageDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditImageDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.images.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + params.push(("imageType", self._image_type.to_string())); + params.push(("imageId", self._image_id.to_string())); + for &field in ["packageName", "editId", "language", "imageType", "imageId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}/{imageId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language"), ("{imageType}", "imageType"), ("{imageId}", "imageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(5); + for param_name in ["packageName", "editId", "language", "imageType", "imageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditImageDeleteCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditImageDeleteCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing whose images are to read or modified. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditImageDeleteCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *image type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn image_type(mut self, new_value: &str) -> EditImageDeleteCall<'a, C, NC, A> { + self._image_type = new_value.to_string(); + self + } + /// Sets the *image id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier an image within the set of images attached to this edit. + pub fn image_id(mut self, new_value: &str) -> EditImageDeleteCall<'a, C, NC, A> { + self._image_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditImageDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditImageDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditImageDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *apks.upload* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apks_upload("packageName", "editId") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct EditApkUploadCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApkUploadCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApkUploadCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, Apk)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apks.upload", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + if protocol == "simple" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + req = req.header(ContentType(reader_mime_type.clone())) + .header(ContentLength(size)) + .body(&mut reader); + } + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 1GB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' and 'application/vnd.android.package-archive' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Apk)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 1GB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' and 'application/vnd.android.package-archive' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Apk)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApkUploadCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApkUploadCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApkUploadCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApkUploadCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApkUploadCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates or creates the APK-specific localized listing for a specified APK and language code. +/// +/// A builder for the *apklistings.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::ApkListing; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ApkListing = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_update(&req, "packageName", "editId", -95, "language") +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: ApkListing, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApkListing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ApkListing) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the APK-specific localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *apks.list* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apks_list("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditApkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApksListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApkListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApkListCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates or creates the APK-specific localized listing for a specified APK and language code. This method supports patch semantics. +/// +/// A builder for the *apklistings.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::ApkListing; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ApkListing = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_patch(&req, "packageName", "editId", -5, "language") +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: ApkListing, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApkListing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ApkListing) -> EditApklistingPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingPatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingPatchCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the APK-specific localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditApklistingPatchCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetches information about a localized store listing. +/// +/// A builder for the *listings.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_get("packageName", "editId", "language") +/// .doit(); +/// # } +/// ``` +pub struct EditListingGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Listing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditListingGetCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *testers.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().testers_get("packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTesterGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTesterGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTesterGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Testers)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.testers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/testers/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTesterGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTesterGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn track(mut self, new_value: &str) -> EditTesterGetCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTesterGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTesterGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTesterGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an edit for an app. Creating a new edit will automatically delete any of your previous edits so this method need only be called if you want to preemptively abandon an edit. +/// +/// A builder for the *delete* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().delete("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditDeleteCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditDeleteCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Uploads and attaches a new Expansion File to the APK specified. +/// +/// A builder for the *expansionfiles.upload* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().expansionfiles_upload("packageName", "editId", -66, "expansionFileType") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct EditExpansionfileUploadCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _expansion_file_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditExpansionfileUploadCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditExpansionfileUploadCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, ExpansionFilesUploadResponse)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.expansionfiles.upload", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("expansionFileType", self._expansion_file_type.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{expansionFileType}", "expansionFileType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + if protocol == "simple" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + req = req.header(ContentType(reader_mime_type.clone())) + .header(ContentLength(size)) + .body(&mut reader); + } + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 2048MB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, ExpansionFilesUploadResponse)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 2048MB + /// * *multipart*: yes + /// * *valid mime types*: 'application/octet-stream' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, ExpansionFilesUploadResponse)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditExpansionfileUploadCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditExpansionfileUploadCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The version code of the APK whose Expansion File configuration is being read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditExpansionfileUploadCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *expansion file type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn expansion_file_type(mut self, new_value: &str) -> EditExpansionfileUploadCall<'a, C, NC, A> { + self._expansion_file_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditExpansionfileUploadCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditExpansionfileUploadCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditExpansionfileUploadCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new edit for an app, populated with the app's current state. +/// +/// A builder for the *insert* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::AppEdit; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AppEdit = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().insert(&req, "packageName") +/// .doit(); +/// # } +/// ``` +pub struct EditInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: AppEdit, + _package_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppEdit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + for &field in ["alt", "packageName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["packageName"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AppEdit) -> EditInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditInsertCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns all of the localized store listings attached to this edit. +/// +/// A builder for the *listings.list* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_list("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditListingListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListingsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingListCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *testers.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Testers; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Testers = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().testers_patch(&req, "packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTesterPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Testers, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTesterPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTesterPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Testers)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.testers.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/testers/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Testers) -> EditTesterPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTesterPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTesterPatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn track(mut self, new_value: &str) -> EditTesterPatchCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTesterPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTesterPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTesterPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Commits/applies the changes made in this edit back to the app. +/// +/// A builder for the *commit* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().commit("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditCommitCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditCommitCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditCommitCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppEdit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.commit", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}:commit".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditCommitCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditCommitCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditCommitCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditCommitCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditCommitCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all the track configurations for this edit. +/// +/// A builder for the *tracks.list* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().tracks_list("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditTrackListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTrackListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTrackListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TracksListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.tracks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/tracks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTrackListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTrackListCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTrackListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTrackListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTrackListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Checks that the edit can be successfully committed. The edit's changes are not applied to the live app. +/// +/// A builder for the *validate* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().validate("packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditValidateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditValidateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditValidateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppEdit)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.validate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}:validate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditValidateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditValidateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditValidateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditValidateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditValidateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates or updates a localized store listing. +/// +/// A builder for the *listings.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Listing; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Listing = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_update(&req, "packageName", "editId", "language") +/// .doit(); +/// # } +/// ``` +pub struct EditListingUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Listing, + _package_name: String, + _edit_id: String, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Listing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Listing) -> EditListingUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditListingUpdateCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetches the Expansion File configuration for the APK specified. +/// +/// A builder for the *expansionfiles.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().expansionfiles_get("packageName", "editId", -54, "expansionFileType") +/// .doit(); +/// # } +/// ``` +pub struct EditExpansionfileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _expansion_file_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditExpansionfileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditExpansionfileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ExpansionFile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.expansionfiles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("expansionFileType", self._expansion_file_type.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{expansionFileType}", "expansionFileType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "expansionFileType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditExpansionfileGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditExpansionfileGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The version code of the APK whose Expansion File configuration is being read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditExpansionfileGetCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *expansion file type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn expansion_file_type(mut self, new_value: &str) -> EditExpansionfileGetCall<'a, C, NC, A> { + self._expansion_file_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditExpansionfileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditExpansionfileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditExpansionfileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes all images for the specified language and image type. +/// +/// A builder for the *images.deleteall* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().images_deleteall("packageName", "editId", "language", "imageType") +/// .doit(); +/// # } +/// ``` +pub struct EditImageDeleteallCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _image_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditImageDeleteallCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditImageDeleteallCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ImagesDeleteAllResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.images.deleteall", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + params.push(("imageType", self._image_type.to_string())); + for &field in ["alt", "packageName", "editId", "language", "imageType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language"), ("{imageType}", "imageType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "language", "imageType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditImageDeleteallCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditImageDeleteallCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing whose images are to read or modified. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditImageDeleteallCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *image type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn image_type(mut self, new_value: &str) -> EditImageDeleteallCall<'a, C, NC, A> { + self._image_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditImageDeleteallCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditImageDeleteallCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditImageDeleteallCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates app details for this edit. This method supports patch semantics. +/// +/// A builder for the *details.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::AppDetails; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AppDetails = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().details_patch(&req, "packageName", "editId") +/// .doit(); +/// # } +/// ``` +pub struct EditDetailPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: AppDetails, + _package_name: String, + _edit_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditDetailPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditDetailPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppDetails)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.details.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + for &field in ["alt", "packageName", "editId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/details".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "editId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AppDetails) -> EditDetailPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditDetailPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditDetailPatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditDetailPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditDetailPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditDetailPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the track configuration for the specified track type. When halted, the rollout track cannot be updated without adding new APKs, and adding new APKs will cause it to resume. This method supports patch semantics. +/// +/// A builder for the *tracks.patch* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Track; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Track = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().tracks_patch(&req, "packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTrackPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Track, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTrackPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTrackPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Track)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.tracks.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/tracks/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Track) -> EditTrackPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTrackPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTrackPatchCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The track type to read or modify. + pub fn track(mut self, new_value: &str) -> EditTrackPatchCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTrackPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTrackPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTrackPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified localized store listing from an edit. +/// +/// A builder for the *listings.delete* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().listings_delete("packageName", "editId", "language") +/// .doit(); +/// # } +/// ``` +pub struct EditListingDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditListingDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditListingDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.listings.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["packageName", "editId", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditListingDeleteCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditListingDeleteCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditListingDeleteCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditListingDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditListingDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditListingDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetches the APK-specific localized listing for a specified APK and language code. +/// +/// A builder for the *apklistings.get* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_get("packageName", "editId", -87, "language") +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _language: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApkListing)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + params.push(("language", self._language.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode", "language"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings/{language}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode"), ("{language}", "language")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(4); + for param_name in ["packageName", "editId", "apkVersionCode", "language"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingGetCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingGetCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *language* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The language code (a BCP-47 language tag) of the APK-specific localized listing to read or modify. For example, to select Austrian German, pass "de-AT". + pub fn language(mut self, new_value: &str) -> EditApklistingGetCall<'a, C, NC, A> { + self._language = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *testers.update* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::Testers; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Testers = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().testers_update(&req, "packageName", "editId", "track") +/// .doit(); +/// # } +/// ``` +pub struct EditTesterUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: Testers, + _package_name: String, + _edit_id: String, + _track: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditTesterUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditTesterUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Testers)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.testers.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("track", self._track.to_string())); + for &field in ["alt", "packageName", "editId", "track"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/testers/{track}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{track}", "track")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "track"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Testers) -> EditTesterUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditTesterUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditTesterUpdateCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *track* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn track(mut self, new_value: &str) -> EditTesterUpdateCall<'a, C, NC, A> { + self._track = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditTesterUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditTesterUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditTesterUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all the APK-specific localized listings for a specified APK. +/// +/// A builder for the *apklistings.list* method supported by a *edit* resource. +/// It is not used directly, but through a `EditMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.edits().apklistings_list("packageName", "editId", -67) +/// .doit(); +/// # } +/// ``` +pub struct EditApklistingListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _edit_id: String, + _apk_version_code: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EditApklistingListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EditApklistingListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ApkListingsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.edits.apklistings.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("editId", self._edit_id.to_string())); + params.push(("apkVersionCode", self._apk_version_code.to_string())); + for &field in ["alt", "packageName", "editId", "apkVersionCode"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/listings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{editId}", "editId"), ("{apkVersionCode}", "apkVersionCode")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["packageName", "editId", "apkVersionCode"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app that is being updated; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> EditApklistingListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *edit id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for this edit. + pub fn edit_id(mut self, new_value: &str) -> EditApklistingListCall<'a, C, NC, A> { + self._edit_id = new_value.to_string(); + self + } + /// Sets the *apk version code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The APK version code whose APK-specific listings should be read or modified. + pub fn apk_version_code(mut self, new_value: i32) -> EditApklistingListCall<'a, C, NC, A> { + self._apk_version_code = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EditApklistingListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EditApklistingListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EditApklistingListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *batch* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::InappproductsBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InappproductsBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().batch(&req) +/// .doit(); +/// # } +/// ``` +pub struct InappproductBatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: InappproductsBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductBatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductBatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InappproductsBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.batch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/inappproducts/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InappproductsBatchRequest) -> InappproductBatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductBatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductBatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductBatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List all the in-app products for an Android app, both subscriptions and managed in-app products.. +/// +/// A builder for the *list* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().list("packageName") +/// .token("et") +/// .start_index(53) +/// .max_results(60) +/// .doit(); +/// # } +/// ``` +pub struct InappproductListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _token: Option, + _start_index: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InappproductsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + if let Some(value) = self._token { + params.push(("token", value.to_string())); + } + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "packageName", "token", "startIndex", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["packageName"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app with in-app products; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> InappproductListCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *token* query property to the given value. + /// + /// + pub fn token(mut self, new_value: &str) -> InappproductListCall<'a, C, NC, A> { + self._token = Some(new_value.to_string()); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + pub fn start_index(mut self, new_value: u32) -> InappproductListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + pub fn max_results(mut self, new_value: u32) -> InappproductListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new in-app product for an app. +/// +/// A builder for the *insert* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::InAppProduct; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InAppProduct = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().insert(&req, "packageName") +/// .auto_convert_missing_prices(false) +/// .doit(); +/// # } +/// ``` +pub struct InappproductInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: InAppProduct, + _package_name: String, + _auto_convert_missing_prices: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InAppProduct)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + if let Some(value) = self._auto_convert_missing_prices { + params.push(("autoConvertMissingPrices", value.to_string())); + } + for &field in ["alt", "packageName", "autoConvertMissingPrices"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["packageName"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InAppProduct) -> InappproductInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> InappproductInsertCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *auto convert missing prices* query property to the given value. + /// + /// + /// If true the prices for all regions targeted by the parent app that don't have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. + pub fn auto_convert_missing_prices(mut self, new_value: bool) -> InappproductInsertCall<'a, C, NC, A> { + self._auto_convert_missing_prices = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete an in-app product for an app. +/// +/// A builder for the *delete* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().delete("packageName", "sku") +/// .doit(); +/// # } +/// ``` +pub struct InappproductDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _sku: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("sku", self._sku.to_string())); + for &field in ["packageName", "sku"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{sku}", "sku")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "sku"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app with the in-app product; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> InappproductDeleteCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *sku* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the in-app product. + pub fn sku(mut self, new_value: &str) -> InappproductDeleteCall<'a, C, NC, A> { + self._sku = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns information about the in-app product specified. +/// +/// A builder for the *get* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().get("packageName", "sku") +/// .doit(); +/// # } +/// ``` +pub struct InappproductGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _package_name: String, + _sku: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InAppProduct)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("sku", self._sku.to_string())); + for &field in ["alt", "packageName", "sku"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{sku}", "sku")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "sku"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn package_name(mut self, new_value: &str) -> InappproductGetCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *sku* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the in-app product. + pub fn sku(mut self, new_value: &str) -> InappproductGetCall<'a, C, NC, A> { + self._sku = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the details of an in-app product. +/// +/// A builder for the *update* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::InAppProduct; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InAppProduct = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().update(&req, "packageName", "sku") +/// .auto_convert_missing_prices(false) +/// .doit(); +/// # } +/// ``` +pub struct InappproductUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: InAppProduct, + _package_name: String, + _sku: String, + _auto_convert_missing_prices: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InAppProduct)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("sku", self._sku.to_string())); + if let Some(value) = self._auto_convert_missing_prices { + params.push(("autoConvertMissingPrices", value.to_string())); + } + for &field in ["alt", "packageName", "sku", "autoConvertMissingPrices"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{sku}", "sku")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "sku"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InAppProduct) -> InappproductUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app with the in-app product; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> InappproductUpdateCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *sku* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the in-app product. + pub fn sku(mut self, new_value: &str) -> InappproductUpdateCall<'a, C, NC, A> { + self._sku = new_value.to_string(); + self + } + /// Sets the *auto convert missing prices* query property to the given value. + /// + /// + /// If true the prices for all regions targeted by the parent app that don't have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. + pub fn auto_convert_missing_prices(mut self, new_value: bool) -> InappproductUpdateCall<'a, C, NC, A> { + self._auto_convert_missing_prices = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the details of an in-app product. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *inappproduct* resource. +/// It is not used directly, but through a `InappproductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-androidpublisher2" as androidpublisher2; +/// use androidpublisher2::InAppProduct; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use androidpublisher2::AndroidPublisher; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AndroidPublisher::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InAppProduct = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inappproducts().patch(&req, "packageName", "sku") +/// .auto_convert_missing_prices(true) +/// .doit(); +/// # } +/// ``` +pub struct InappproductPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AndroidPublisher, + _request: InAppProduct, + _package_name: String, + _sku: String, + _auto_convert_missing_prices: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InappproductPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InappproductPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InAppProduct)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "androidpublisher.inappproducts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("packageName", self._package_name.to_string())); + params.push(("sku", self._sku.to_string())); + if let Some(value) = self._auto_convert_missing_prices { + params.push(("autoConvertMissingPrices", value.to_string())); + } + for &field in ["alt", "packageName", "sku", "autoConvertMissingPrices"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/androidpublisher/v2/applications/{packageName}/inappproducts/{sku}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{packageName}", "packageName"), ("{sku}", "sku")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["packageName", "sku"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InAppProduct) -> InappproductPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *package name* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the Android app with the in-app product; for example, "com.spiffygame". + pub fn package_name(mut self, new_value: &str) -> InappproductPatchCall<'a, C, NC, A> { + self._package_name = new_value.to_string(); + self + } + /// Sets the *sku* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Unique identifier for the in-app product. + pub fn sku(mut self, new_value: &str) -> InappproductPatchCall<'a, C, NC, A> { + self._sku = new_value.to_string(); + self + } + /// Sets the *auto convert missing prices* query property to the given value. + /// + /// + /// If true the prices for all regions targeted by the parent app that don't have a price specified for this in-app product will be auto converted to the target currency based on the default price. Defaults to false. + pub fn auto_convert_missing_prices(mut self, new_value: bool) -> InappproductPatchCall<'a, C, NC, A> { + self._auto_convert_missing_prices = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InappproductPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InappproductPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InappproductPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/appsactivity1/Cargo.toml b/gen/appsactivity1/Cargo.toml new file mode 100644 index 0000000000..d8de1810da --- /dev/null +++ b/gen/appsactivity1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-appsactivity1" +version = "0.1.0+20140828" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with appsactivity (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/appsactivity1" +homepage = "https://developers.google.com/google-apps/activity/" +documentation = "http://byron.github.io/google-apis-rs/google-appsactivity1" +license = "MIT" +keywords = ["appsactivity", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/appsactivity1/LICENSE.md b/gen/appsactivity1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/appsactivity1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/appsactivity1/README.md b/gen/appsactivity1/README.md new file mode 100644 index 0000000000..7ffaf8d84a --- /dev/null +++ b/gen/appsactivity1/README.md @@ -0,0 +1,170 @@ + +The `google-appsactivity1` library allows access to all features of the *Google appsactivity* service. + +This documentation was generated from *appsactivity* crate version *0.1.0+20140828*, where *20140828* is the exact revision of the *appsactivity:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *appsactivity* *v1* API can be found at the +[official documentation site](https://developers.google.com/google-apps/activity/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-appsactivity1/struct.Appsactivity.html) ... + +* [activities](http://byron.github.io/google-apis-rs/google-appsactivity1/struct.Activity.html) + * [*list*](http://byron.github.io/google-apis-rs/google-appsactivity1/struct.ActivityListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-appsactivity1/struct.Appsactivity.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.activities().list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-appsactivity1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-appsactivity1" as appsactivity1; +use appsactivity1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use appsactivity1::Appsactivity; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Appsactivity::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.activities().list() + .user_id("eirmod") + .source("sit") + .page_token("Stet") + .page_size(-42) + .grouping_strategy("et") + .drive_file_id("dolores") + .drive_ancestor_id("kasd") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-appsactivity1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-appsactivity1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-appsactivity1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-appsactivity1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **appsactivity1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/appsactivity1/src/cmn.rs b/gen/appsactivity1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/appsactivity1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/appsactivity1/src/lib.rs b/gen/appsactivity1/src/lib.rs new file mode 100644 index 0000000000..0745b585e2 --- /dev/null +++ b/gen/appsactivity1/src/lib.rs @@ -0,0 +1,912 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *appsactivity* crate version *0.1.0+20140828*, where *20140828* is the exact revision of the *appsactivity:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *appsactivity* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/google-apps/activity/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/appsactivity1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Appsactivity.html) ... +//! +//! * [activities](struct.Activity.html) +//! * [*list*](struct.ActivityListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Appsactivity.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.activities().list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-appsactivity1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-appsactivity1" as appsactivity1; +//! use appsactivity1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use appsactivity1::Appsactivity; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Appsactivity::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.activities().list() +//! .user_id("accusam") +//! .source("takimata") +//! .page_token("justo") +//! .page_size(-1) +//! .grouping_strategy("erat") +//! .drive_file_id("labore") +//! .drive_ancestor_id("sea") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage the files in your Google Drive + Drive, + + /// View the activity history of your Google Apps + Activity, + + /// View metadata for files in your Google Drive + DriveMetadataReadonly, + + /// View the files in your Google Drive + DriveReadonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Drive => "https://www.googleapis.com/auth/drive", + Scope::Activity => "https://www.googleapis.com/auth/activity", + Scope::DriveMetadataReadonly => "https://www.googleapis.com/auth/drive.metadata.readonly", + Scope::DriveReadonly => "https://www.googleapis.com/auth/drive.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::DriveMetadataReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Appsactivity related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-appsactivity1" as appsactivity1; +/// use appsactivity1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appsactivity1::Appsactivity; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Appsactivity::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().list() +/// .user_id("nonumy") +/// .source("dolores") +/// .page_token("gubergren") +/// .page_size(-95) +/// .grouping_strategy("aliquyam") +/// .drive_file_id("ea") +/// .drive_ancestor_id("no") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Appsactivity { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Appsactivity {} + +impl<'a, C, NC, A> Appsactivity + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Appsactivity { + Appsactivity { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn activities(&'a self) -> ActivityMethods<'a, C, NC, A> { + ActivityMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Contains information about a renametype event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Rename { + /// The new title. + #[serde(alias="newTitle")] + pub new_title: String, + /// The old title. + #[serde(alias="oldTitle")] + pub old_title: String, +} + +impl Part for Rename {} + + +/// Contains information about a Drive object's permissions that changed as a result of a permissionChange type event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PermissionChange { + /// Lists all Permission objects removed. + #[serde(alias="removedPermissions")] + pub removed_permissions: Vec, + /// Lists all Permission objects added. + #[serde(alias="addedPermissions")] + pub added_permissions: Vec, +} + +impl Part for PermissionChange {} + + +/// Information about the object modified by the event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Target { + /// The MIME type of the target. + #[serde(alias="mimeType")] + pub mime_type: String, + /// The ID of the target. For example, in Google Drive, this is the file or folder ID. + pub id: String, + /// The name of the target. For example, in Google Drive, this is the title of the file. + pub name: String, +} + +impl Part for Target {} + + +/// Contains information about a parent object. For example, a folder in Drive is a parent for all files within it. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Parent { + /// The parent's ID. + pub id: String, + /// Whether this is the root folder. + #[serde(alias="isRoot")] + pub is_root: bool, + /// The parent's title. + pub title: String, +} + +impl Part for Parent {} + + +/// Contains information about the permissions and type of access allowed with regards to a Google Drive object. This is a subset of the fields contained in a corresponding Drive Permissions object. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Permission { + /// Whether the permission requires a link to the file. + #[serde(alias="withLink")] + pub with_link: bool, + /// The ID for this permission. Corresponds to the Drive API's permission ID returned as part of the Drive Permissions resource. + #[serde(alias="permissionId")] + pub permission_id: String, + /// Indicates the Google Drive permissions role. The role determines a user's ability to read, write, or comment on the file. + pub role: String, + /// The name of the user or group the permission applies to. + pub name: String, + /// Indicates how widely permissions are granted. + #[serde(alias="type")] + pub type_: String, + /// The user's information if the type is USER. + pub user: User, +} + +impl Part for Permission {} + + +/// Photo information for a user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Photo { + /// The URL of the photo. + pub url: String, +} + +impl Part for Photo {} + + +/// Contains information about changes in an object's parents as a result of a move type event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Move { + /// The removed parent(s). + #[serde(alias="removedParents")] + pub removed_parents: Vec, + /// The added parent(s). + #[serde(alias="addedParents")] + pub added_parents: Vec, +} + +impl Part for Move {} + + +/// The response from the list request. Contains a list of activities and a token to retrieve the next page of results. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list activities](struct.ActivityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListActivitiesResponse { + /// Token for the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of activities. + pub activities: Vec, +} + +impl ResponseResult for ListActivitiesResponse {} + + +/// A representation of a user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct User { + /// The profile photo of the user. + pub photo: Photo, + /// The displayable name of the user. + pub name: String, +} + +impl Part for User {} + + +/// An Activity resource is a combined view of multiple events. An activity has a list of individual events and a combined view of the common fields among all events. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Activity { + /// The fields common to all of the singleEvents that make up the Activity. + #[serde(alias="combinedEvent")] + pub combined_event: Event, + /// A list of all the Events that make up the Activity. + #[serde(alias="singleEvents")] + pub single_events: Vec, +} + +impl Part for Activity {} + + +/// Represents the changes associated with an action taken by a user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Event { + /// Extra information for rename type events, such as the old and new names. + pub rename: Rename, + /// Information specific to the Target object modified by the event. + pub target: Target, + /// Additional event types. Some events may have multiple types when multiple actions are part of a single event. For example, creating a document, renaming it, and sharing it may be part of a single file-creation event. + #[serde(alias="additionalEventTypes")] + pub additional_event_types: Vec, + /// Extra information for move type events, such as changes in an object's parents. + #[serde(alias="move")] + pub move_: Move, + /// Extra information for permissionChange type events, such as the user or group the new permission applies to. + #[serde(alias="permissionChanges")] + pub permission_changes: Vec, + /// Represents the user responsible for the event. + pub user: User, + /// The time at which the event occurred formatted as Unix time in milliseconds. + #[serde(alias="eventTimeMillis")] + pub event_time_millis: String, + /// The main type of event that occurred. + #[serde(alias="primaryEventType")] + pub primary_event_type: String, + /// Whether this event is caused by a user being deleted. + #[serde(alias="fromUserDeletion")] + pub from_user_deletion: bool, +} + +impl Part for Event {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *activity* resources. +/// It is not used directly, but through the `Appsactivity` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-appsactivity1" as appsactivity1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appsactivity1::Appsactivity; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Appsactivity::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.activities(); +/// # } +/// ``` +pub struct ActivityMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Appsactivity, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ActivityMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of activities visible to the current logged in user. Visible activities are determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter. + pub fn list(&self) -> ActivityListCall<'a, C, NC, A> { + ActivityListCall { + hub: self.hub, + _user_id: Default::default(), + _source: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _grouping_strategy: Default::default(), + _drive_file_id: Default::default(), + _drive_ancestor_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns a list of activities visible to the current logged in user. Visible activities are determined by the visiblity settings of the object that was acted on, e.g. Drive files a user can see. An activity is a record of past events. Multiple events may be merged if they are similar. A request is scoped to activities from a given Google service using the source parameter. +/// +/// A builder for the *list* method supported by a *activity* resource. +/// It is not used directly, but through a `ActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appsactivity1" as appsactivity1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appsactivity1::Appsactivity; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appsactivity::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().list() +/// .user_id("justo") +/// .source("justo") +/// .page_token("et") +/// .page_size(-17) +/// .grouping_strategy("diam") +/// .drive_file_id("ipsum") +/// .drive_ancestor_id("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct ActivityListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Appsactivity, + _user_id: Option, + _source: Option, + _page_token: Option, + _page_size: Option, + _grouping_strategy: Option, + _drive_file_id: Option, + _drive_ancestor_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ActivityListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListActivitiesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appsactivity.activities.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + if let Some(value) = self._user_id { + params.push(("userId", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._page_size { + params.push(("pageSize", value.to_string())); + } + if let Some(value) = self._grouping_strategy { + params.push(("groupingStrategy", value.to_string())); + } + if let Some(value) = self._drive_file_id { + params.push(("drive.fileId", value.to_string())); + } + if let Some(value) = self._drive_ancestor_id { + params.push(("drive.ancestorId", value.to_string())); + } + for &field in ["alt", "userId", "source", "pageToken", "pageSize", "groupingStrategy", "drive.fileId", "drive.ancestorId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/appsactivity/v1/activities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DriveMetadataReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* query property to the given value. + /// + /// + /// Indicates the user to return activity for. Use the special value me to indicate the currently authenticated user. + pub fn user_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._user_id = Some(new_value.to_string()); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// The Google service from which to return activities. Possible values of source are: + /// - drive.google.com + pub fn source(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// A token to retrieve a specific page of results. + pub fn page_token(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *page size* query property to the given value. + /// + /// + /// The maximum number of events to return on a page. The response includes a continuation token if there are more events. + pub fn page_size(mut self, new_value: i32) -> ActivityListCall<'a, C, NC, A> { + self._page_size = Some(new_value); + self + } + /// Sets the *grouping strategy* query property to the given value. + /// + /// + /// Indicates the strategy to use when grouping singleEvents items in the associated combinedEvent object. + pub fn grouping_strategy(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._grouping_strategy = Some(new_value.to_string()); + self + } + /// Sets the *drive.file id* query property to the given value. + /// + /// + /// Identifies the Drive item to return activities for. + pub fn drive_file_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._drive_file_id = Some(new_value.to_string()); + self + } + /// Sets the *drive.ancestor id* query property to the given value. + /// + /// + /// Identifies the Drive folder containing the items for which to return activities. + pub fn drive_ancestor_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._drive_ancestor_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ActivityListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ActivityListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ActivityListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/appstate1/Cargo.toml b/gen/appstate1/Cargo.toml new file mode 100644 index 0000000000..42bbeb6fce --- /dev/null +++ b/gen/appstate1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-appstate1" +version = "0.1.0+20150309" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with App State (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/appstate1" +homepage = "https://developers.google.com/games/services/web/api/states" +documentation = "http://byron.github.io/google-apis-rs/google-appstate1" +license = "MIT" +keywords = ["appstate", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/appstate1/LICENSE.md b/gen/appstate1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/appstate1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/appstate1/README.md b/gen/appstate1/README.md new file mode 100644 index 0000000000..f7575e7b01 --- /dev/null +++ b/gen/appstate1/README.md @@ -0,0 +1,171 @@ + +The `google-appstate1` library allows access to all features of the *Google App State* service. + +This documentation was generated from *App State* crate version *0.1.0+20150309*, where *20150309* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *App State* *v1* API can be found at the +[official documentation site](https://developers.google.com/games/services/web/api/states). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-appstate1/struct.AppState.html) ... + +* states + * [*clear*](http://byron.github.io/google-apis-rs/google-appstate1/struct.StateClearCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-appstate1/struct.StateDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-appstate1/struct.StateGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-appstate1/struct.StateListCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-appstate1/struct.StateUpdateCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-appstate1/struct.AppState.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-appstate1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-appstate1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-appstate1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.states().clear(...).doit() +let r = hub.states().update(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-appstate1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-appstate1" as appstate1; +use appstate1::UpdateRequest; +use appstate1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use appstate1::AppState; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AppState::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: UpdateRequest = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.states().update(&req, -39) + .current_state_version("sit") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-appstate1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-appstate1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-appstate1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-appstate1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-appstate1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-appstate1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-appstate1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-appstate1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-appstate1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-appstate1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-appstate1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-appstate1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-appstate1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **appstate1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/appstate1/src/cmn.rs b/gen/appstate1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/appstate1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/appstate1/src/lib.rs b/gen/appstate1/src/lib.rs new file mode 100644 index 0000000000..999a83604a --- /dev/null +++ b/gen/appstate1/src/lib.rs @@ -0,0 +1,1718 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *App State* crate version *0.1.0+20150309*, where *20150309* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *App State* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/games/services/web/api/states). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/appstate1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AppState.html) ... +//! +//! * states +//! * [*clear*](struct.StateClearCall.html), [*delete*](struct.StateDeleteCall.html), [*get*](struct.StateGetCall.html), [*list*](struct.StateListCall.html) and [*update*](struct.StateUpdateCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AppState.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.states().clear(...).doit() +//! let r = hub.states().update(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-appstate1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-appstate1" as appstate1; +//! use appstate1::UpdateRequest; +//! use appstate1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use appstate1::AppState; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AppState::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: UpdateRequest = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.states().update(&req, -65) +//! .current_state_version("sed") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your data for this application + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/appstate", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AppState related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-appstate1" as appstate1; +/// use appstate1::UpdateRequest; +/// use appstate1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appstate1::AppState; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AppState::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UpdateRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().update(&req, -85) +/// .current_state_version("dolores") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AppState { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AppState {} + +impl<'a, C, NC, A> AppState + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AppState { + AppState { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn states(&'a self) -> StateMethods<'a, C, NC, A> { + StateMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// This is a JSON template to convert a list-response for app state. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list states](struct.StateListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListResponse { + /// The app state data. + pub items: Vec, + /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#listResponse. + pub kind: String, + /// The maximum number of keys allowed for this user. + #[serde(alias="maximumKeyCount")] + pub maximum_key_count: i32, +} + +impl ResponseResult for ListResponse {} + + +/// This is a JSON template for an app state resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get states](struct.StateGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GetResponse { + /// The requested data. + pub data: String, + /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#getResponse. + pub kind: String, + /// The key for the data. + #[serde(alias="stateKey")] + pub state_key: i32, + /// The current app state version. + #[serde(alias="currentStateVersion")] + pub current_state_version: String, +} + +impl ResponseResult for GetResponse {} + + +/// This is a JSON template for a requests which update app state +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update states](struct.StateUpdateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UpdateRequest { + /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#updateRequest. + pub kind: Option, + /// The new app state data that your application is trying to update with. + pub data: Option, +} + +impl RequestValue for UpdateRequest {} + + +/// This is a JSON template for an app state write result. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [clear states](struct.StateClearCall.html) (response) +/// * [update states](struct.StateUpdateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct WriteResult { + /// Uniquely identifies the type of this resource. Value is always the fixed string appstate#writeResult. + pub kind: String, + /// The written key. + #[serde(alias="stateKey")] + pub state_key: i32, + /// The version of the data for this key on the server. + #[serde(alias="currentStateVersion")] + pub current_state_version: String, +} + +impl ResponseResult for WriteResult {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *state* resources. +/// It is not used directly, but through the `AppState` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-appstate1" as appstate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appstate1::AppState; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AppState::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `clear(...)`, `delete(...)`, `get(...)`, `list(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.states(); +/// # } +/// ``` +pub struct StateMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for StateMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption. + pub fn delete(&self, state_key: i32) -> StateDeleteCall<'a, C, NC, A> { + StateDeleteCall { + hub: self.hub, + _state_key: state_key, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned. + pub fn get(&self, state_key: i32) -> StateGetCall<'a, C, NC, A> { + StateGetCall { + hub: self.hub, + _state_key: state_key, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch. + pub fn clear(&self, state_key: i32) -> StateClearCall<'a, C, NC, A> { + StateClearCall { + hub: self.hub, + _state_key: state_key, + _current_data_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all the states keys, and optionally the state data. + pub fn list(&self) -> StateListCall<'a, C, NC, A> { + StateListCall { + hub: self.hub, + _include_data: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB. + pub fn update(&self, request: &UpdateRequest, state_key: i32) -> StateUpdateCall<'a, C, NC, A> { + StateUpdateCall { + hub: self.hub, + _request: request.clone(), + _state_key: state_key, + _current_state_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption. +/// +/// A builder for the *delete* method supported by a *state* resource. +/// It is not used directly, but through a `StateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appstate1" as appstate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appstate1::AppState; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AppState::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().delete(-63) +/// .doit(); +/// # } +/// ``` +pub struct StateDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, + _state_key: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StateDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appstate.states.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("stateKey", self._state_key.to_string())); + for &field in ["stateKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/appstate/v1/states/{stateKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["stateKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *state key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key for the data to be retrieved. + pub fn state_key(mut self, new_value: i32) -> StateDeleteCall<'a, C, NC, A> { + self._state_key = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StateDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StateDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StateDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned. +/// +/// A builder for the *get* method supported by a *state* resource. +/// It is not used directly, but through a `StateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appstate1" as appstate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appstate1::AppState; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AppState::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().get(-22) +/// .doit(); +/// # } +/// ``` +pub struct StateGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, + _state_key: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StateGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appstate.states.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("stateKey", self._state_key.to_string())); + for &field in ["alt", "stateKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/appstate/v1/states/{stateKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["stateKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *state key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key for the data to be retrieved. + pub fn state_key(mut self, new_value: i32) -> StateGetCall<'a, C, NC, A> { + self._state_key = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StateGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StateGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StateGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch. +/// +/// A builder for the *clear* method supported by a *state* resource. +/// It is not used directly, but through a `StateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appstate1" as appstate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appstate1::AppState; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AppState::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().clear(-8) +/// .current_data_version("justo") +/// .doit(); +/// # } +/// ``` +pub struct StateClearCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, + _state_key: i32, + _current_data_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StateClearCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateClearCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, WriteResult)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appstate.states.clear", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("stateKey", self._state_key.to_string())); + if let Some(value) = self._current_data_version { + params.push(("currentDataVersion", value.to_string())); + } + for &field in ["alt", "stateKey", "currentDataVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/appstate/v1/states/{stateKey}/clear".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["stateKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *state key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key for the data to be retrieved. + pub fn state_key(mut self, new_value: i32) -> StateClearCall<'a, C, NC, A> { + self._state_key = new_value; + self + } + /// Sets the *current data version* query property to the given value. + /// + /// + /// The version of the data to be cleared. Version strings are returned by the server. + pub fn current_data_version(mut self, new_value: &str) -> StateClearCall<'a, C, NC, A> { + self._current_data_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StateClearCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StateClearCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StateClearCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all the states keys, and optionally the state data. +/// +/// A builder for the *list* method supported by a *state* resource. +/// It is not used directly, but through a `StateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appstate1" as appstate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appstate1::AppState; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AppState::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().list() +/// .include_data(true) +/// .doit(); +/// # } +/// ``` +pub struct StateListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, + _include_data: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StateListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appstate.states.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + if let Some(value) = self._include_data { + params.push(("includeData", value.to_string())); + } + for &field in ["alt", "includeData"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/appstate/v1/states".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *include data* query property to the given value. + /// + /// + /// Whether to include the full data in addition to the version number + pub fn include_data(mut self, new_value: bool) -> StateListCall<'a, C, NC, A> { + self._include_data = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StateListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StateListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StateListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB. +/// +/// A builder for the *update* method supported by a *state* resource. +/// It is not used directly, but through a `StateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-appstate1" as appstate1; +/// use appstate1::UpdateRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appstate1::AppState; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AppState::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UpdateRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.states().update(&req, -81) +/// .current_state_version("labore") +/// .doit(); +/// # } +/// ``` +pub struct StateUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AppState, + _request: UpdateRequest, + _state_key: i32, + _current_state_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StateUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StateUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, WriteResult)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appstate.states.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("stateKey", self._state_key.to_string())); + if let Some(value) = self._current_state_version { + params.push(("currentStateVersion", value.to_string())); + } + for &field in ["alt", "stateKey", "currentStateVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/appstate/v1/states/{stateKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{stateKey}", "stateKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["stateKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UpdateRequest) -> StateUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *state key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key for the data to be retrieved. + pub fn state_key(mut self, new_value: i32) -> StateUpdateCall<'a, C, NC, A> { + self._state_key = new_value; + self + } + /// Sets the *current state version* query property to the given value. + /// + /// + /// The version of the app state your application is attempting to update. If this does not match the current version, this method will return a conflict error. If there is no data stored on the server for this key, the update will succeed irrespective of the value of this parameter. + pub fn current_state_version(mut self, new_value: &str) -> StateUpdateCall<'a, C, NC, A> { + self._current_state_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StateUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StateUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StateUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/audit1/Cargo.toml b/gen/audit1/Cargo.toml new file mode 100644 index 0000000000..d99f47c997 --- /dev/null +++ b/gen/audit1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-audit1" +version = "0.1.0+20130108" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with audit (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/audit1" +homepage = "https://developers.google.com/google-apps/admin-audit/get_started" +documentation = "http://byron.github.io/google-apis-rs/google-audit1" +license = "MIT" +keywords = ["audit", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/audit1/LICENSE.md b/gen/audit1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/audit1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/audit1/README.md b/gen/audit1/README.md new file mode 100644 index 0000000000..814e958714 --- /dev/null +++ b/gen/audit1/README.md @@ -0,0 +1,172 @@ + +The `google-audit1` library allows access to all features of the *Google audit* service. + +This documentation was generated from *audit* crate version *0.1.0+20130108*, where *20130108* is the exact revision of the *audit:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *audit* *v1* API can be found at the +[official documentation site](https://developers.google.com/google-apps/admin-audit/get_started). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-audit1/struct.Audit.html) ... + +* [activities](http://byron.github.io/google-apis-rs/google-audit1/struct.Activity.html) + * [*list*](http://byron.github.io/google-apis-rs/google-audit1/struct.ActivityListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-audit1/struct.Audit.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-audit1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-audit1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-audit1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.activities().list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-audit1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-audit1" as audit1; +use audit1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use audit1::Audit; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Audit::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.activities().list("customerId", "applicationId") + .start_time("Stet") + .max_results(-42) + .event_name("et") + .end_time("dolores") + .continuation_token("kasd") + .caller("accusam") + .actor_ip_address("takimata") + .actor_email("justo") + .actor_application_id("amet.") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-audit1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-audit1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-audit1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-audit1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-audit1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-audit1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-audit1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-audit1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-audit1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-audit1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-audit1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-audit1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-audit1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **audit1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/audit1/src/cmn.rs b/gen/audit1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/audit1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/audit1/src/lib.rs b/gen/audit1/src/lib.rs new file mode 100644 index 0000000000..e1b06e7f51 --- /dev/null +++ b/gen/audit1/src/lib.rs @@ -0,0 +1,852 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *audit* crate version *0.1.0+20130108*, where *20130108* is the exact revision of the *audit:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *audit* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/google-apps/admin-audit/get_started). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/audit1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Audit.html) ... +//! +//! * [activities](struct.Activity.html) +//! * [*list*](struct.ActivityListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Audit.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.activities().list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-audit1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-audit1" as audit1; +//! use audit1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use audit1::Audit; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Audit::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.activities().list("customerId", "applicationId") +//! .start_time("sea") +//! .max_results(-90) +//! .event_name("dolores") +//! .end_time("gubergren") +//! .continuation_token("sadipscing") +//! .caller("aliquyam") +//! .actor_ip_address("ea") +//! .actor_email("no") +//! .actor_application_id("justo") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Audit related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-audit1" as audit1; +/// use audit1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use audit1::Audit; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Audit::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().list("customerId", "applicationId") +/// .start_time("et") +/// .max_results(-41) +/// .event_name("ipsum") +/// .end_time("Lorem") +/// .continuation_token("et") +/// .caller("duo") +/// .actor_ip_address("aliquyam") +/// .actor_email("sea") +/// .actor_application_id("Lorem") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Audit { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Audit {} + +impl<'a, C, NC, A> Audit + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Audit { + Audit { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn activities(&'a self) -> ActivityMethods<'a, C, NC, A> { + ActivityMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list activities](struct.ActivityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Activities { + /// Each record in read response. + pub items: Vec, + /// Kind of list response this is. + pub kind: String, + /// Next page URL. + pub next: String, +} + +impl ResponseResult for Activities {} + + +/// User doing the action. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityActor { + /// ID of application which interacted on behalf of the user. + #[serde(alias="applicationId")] + pub application_id: String, + /// Email address of the user. + pub email: String, + /// For OAuth 2LO API requests, consumer_key of the requestor. + pub key: String, + /// User or OAuth 2LO request. + #[serde(alias="callerType")] + pub caller_type: String, +} + +impl NestedType for ActivityActor {} +impl Part for ActivityActor {} + + +/// Unique identifier for each activity record. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityId { + /// Unique qualifier if multiple events have the same time. + #[serde(alias="uniqQualifier")] + pub uniq_qualifier: String, + /// Application ID of the source application. + #[serde(alias="applicationId")] + pub application_id: String, + /// Obfuscated customer ID of the source customer. + #[serde(alias="customerId")] + pub customer_id: String, + /// Time of occurrence of the activity. + pub time: String, +} + +impl NestedType for ActivityId {} +impl Part for ActivityId {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Activity { + /// Kind of resource this is. + pub kind: String, + /// Activity events. + pub events: Vec, + /// IP Address of the user doing the action. + #[serde(alias="ipAddress")] + pub ip_address: String, + /// Domain of source customer. + #[serde(alias="ownerDomain")] + pub owner_domain: String, + /// User doing the action. + pub actor: ActivityActor, + /// Unique identifier for each activity record. + pub id: ActivityId, +} + +impl Part for Activity {} + + +/// Event parameters. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityEventsParameters { + /// Name of the parameter. + pub name: String, + /// Value of the parameter. + pub value: String, +} + +impl NestedType for ActivityEventsParameters {} +impl Part for ActivityEventsParameters {} + + +/// Activity events. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ActivityEvents { + /// Type of event. + #[serde(alias="eventType")] + pub event_type: String, + /// Name of event. + pub name: String, + /// Event parameters. + pub parameters: Vec, +} + +impl NestedType for ActivityEvents {} +impl Part for ActivityEvents {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *activity* resources. +/// It is not used directly, but through the `Audit` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-audit1" as audit1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use audit1::Audit; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Audit::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.activities(); +/// # } +/// ``` +pub struct ActivityMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Audit, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ActivityMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of activities for a specific customer and application. + pub fn list(&self, customer_id: &str, application_id: &str) -> ActivityListCall<'a, C, NC, A> { + ActivityListCall { + hub: self.hub, + _customer_id: customer_id.to_string(), + _application_id: application_id.to_string(), + _start_time: Default::default(), + _max_results: Default::default(), + _event_name: Default::default(), + _end_time: Default::default(), + _continuation_token: Default::default(), + _caller: Default::default(), + _actor_ip_address: Default::default(), + _actor_email: Default::default(), + _actor_application_id: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Retrieves a list of activities for a specific customer and application. +/// +/// A builder for the *list* method supported by a *activity* resource. +/// It is not used directly, but through a `ActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-audit1" as audit1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use audit1::Audit; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Audit::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.activities().list("customerId", "applicationId") +/// .start_time("sadipscing") +/// .max_results(-48) +/// .event_name("eirmod") +/// .end_time("elitr") +/// .continuation_token("amet") +/// .caller("no") +/// .actor_ip_address("labore") +/// .actor_email("eirmod") +/// .actor_application_id("dolore") +/// .doit(); +/// # } +/// ``` +pub struct ActivityListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Audit, + _customer_id: String, + _application_id: String, + _start_time: Option, + _max_results: Option, + _event_name: Option, + _end_time: Option, + _continuation_token: Option, + _caller: Option, + _actor_ip_address: Option, + _actor_email: Option, + _actor_application_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for ActivityListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ActivityListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Activities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "audit.activities.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("customerId", self._customer_id.to_string())); + params.push(("applicationId", self._application_id.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._event_name { + params.push(("eventName", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + if let Some(value) = self._continuation_token { + params.push(("continuationToken", value.to_string())); + } + if let Some(value) = self._caller { + params.push(("caller", value.to_string())); + } + if let Some(value) = self._actor_ip_address { + params.push(("actorIpAddress", value.to_string())); + } + if let Some(value) = self._actor_email { + params.push(("actorEmail", value.to_string())); + } + if let Some(value) = self._actor_application_id { + params.push(("actorApplicationId", value.to_string())); + } + for &field in ["alt", "customerId", "applicationId", "startTime", "maxResults", "eventName", "endTime", "continuationToken", "caller", "actorIpAddress", "actorEmail", "actorApplicationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/apps/reporting/audit/v1/{customerId}/{applicationId}".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + for &(find_this, param_name) in [("{customerId}", "customerId"), ("{applicationId}", "applicationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["customerId", "applicationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *customer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Represents the customer who is the owner of target object on which action was performed. + pub fn customer_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._customer_id = new_value.to_string(); + self + } + /// Sets the *application id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Application ID of the application on which the event was performed. + pub fn application_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._application_id = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// Return events which occured at or after this time. + pub fn start_time(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Number of activity records to be shown in each page. + pub fn max_results(mut self, new_value: i32) -> ActivityListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *event name* query property to the given value. + /// + /// + /// Name of the event being queried. + pub fn event_name(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._event_name = Some(new_value.to_string()); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// Return events which occured at or before this time. + pub fn end_time(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *continuation token* query property to the given value. + /// + /// + /// Next page URL. + pub fn continuation_token(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._continuation_token = Some(new_value.to_string()); + self + } + /// Sets the *caller* query property to the given value. + /// + /// + /// Type of the caller. + pub fn caller(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._caller = Some(new_value.to_string()); + self + } + /// Sets the *actor ip address* query property to the given value. + /// + /// + /// IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses. + pub fn actor_ip_address(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._actor_ip_address = Some(new_value.to_string()); + self + } + /// Sets the *actor email* query property to the given value. + /// + /// + /// Email address of the user who performed the action. + pub fn actor_email(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._actor_email = Some(new_value.to_string()); + self + } + /// Sets the *actor application id* query property to the given value. + /// + /// + /// Application ID of the application which interacted on behalf of the user while performing the event. + pub fn actor_application_id(mut self, new_value: &str) -> ActivityListCall<'a, C, NC, A> { + self._actor_application_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ActivityListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ActivityListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + diff --git a/gen/autoscaler1_beta2/Cargo.toml b/gen/autoscaler1_beta2/Cargo.toml new file mode 100644 index 0000000000..26b56ef0cc --- /dev/null +++ b/gen/autoscaler1_beta2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-autoscaler1_beta2" +version = "0.1.0+20141112" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with autoscaler (protocol v1beta2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/autoscaler1_beta2" +homepage = "http://developers.google.com/compute/docs/autoscaler" +documentation = "http://byron.github.io/google-apis-rs/google-autoscaler1_beta2" +license = "MIT" +keywords = ["autoscaler", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/autoscaler1_beta2/LICENSE.md b/gen/autoscaler1_beta2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/autoscaler1_beta2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/autoscaler1_beta2/README.md b/gen/autoscaler1_beta2/README.md new file mode 100644 index 0000000000..a58200cd64 --- /dev/null +++ b/gen/autoscaler1_beta2/README.md @@ -0,0 +1,175 @@ + +The `google-autoscaler1_beta2` library allows access to all features of the *Google autoscaler* service. + +This documentation was generated from *autoscaler* crate version *0.1.0+20141112*, where *20141112* is the exact revision of the *autoscaler:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *autoscaler* *v1_beta2* API can be found at the +[official documentation site](http://developers.google.com/compute/docs/autoscaler). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerHub.html) ... + +* [autoscalers](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.Autoscaler.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerUpdateCall.html) +* zone operations + * [*delete*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.ZoneOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.ZoneOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.ZoneOperationListCall.html) +* [zones](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.Zone.html) + * [*list*](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.ZoneListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/struct.AutoscalerHub.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.autoscalers().list(...).doit() +let r = hub.autoscalers().update(...).doit() +let r = hub.autoscalers().patch(...).doit() +let r = hub.autoscalers().delete(...).doit() +let r = hub.autoscalers().insert(...).doit() +let r = hub.autoscalers().get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-autoscaler1_beta2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +use autoscaler1_beta2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use autoscaler1_beta2::AutoscalerHub; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.autoscalers().list("project", "zone") + .page_token("Stet") + .max_results(59) + .filter("et") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-autoscaler1_beta2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **autoscaler1_beta2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/autoscaler1_beta2/src/cmn.rs b/gen/autoscaler1_beta2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/autoscaler1_beta2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/autoscaler1_beta2/src/lib.rs b/gen/autoscaler1_beta2/src/lib.rs new file mode 100644 index 0000000000..0b078e7699 --- /dev/null +++ b/gen/autoscaler1_beta2/src/lib.rs @@ -0,0 +1,3710 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *autoscaler* crate version *0.1.0+20141112*, where *20141112* is the exact revision of the *autoscaler:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *autoscaler* *v1_beta2* API can be found at the +//! [official documentation site](http://developers.google.com/compute/docs/autoscaler). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/autoscaler1_beta2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.AutoscalerHub.html) ... +//! +//! * [autoscalers](struct.Autoscaler.html) +//! * [*delete*](struct.AutoscalerDeleteCall.html), [*get*](struct.AutoscalerGetCall.html), [*insert*](struct.AutoscalerInsertCall.html), [*list*](struct.AutoscalerListCall.html), [*patch*](struct.AutoscalerPatchCall.html) and [*update*](struct.AutoscalerUpdateCall.html) +//! * zone operations +//! * [*delete*](struct.ZoneOperationDeleteCall.html), [*get*](struct.ZoneOperationGetCall.html) and [*list*](struct.ZoneOperationListCall.html) +//! * [zones](struct.Zone.html) +//! * [*list*](struct.ZoneListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.AutoscalerHub.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.autoscalers().list(...).doit() +//! let r = hub.autoscalers().update(...).doit() +//! let r = hub.autoscalers().patch(...).doit() +//! let r = hub.autoscalers().delete(...).doit() +//! let r = hub.autoscalers().insert(...).doit() +//! let r = hub.autoscalers().get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-autoscaler1_beta2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +//! use autoscaler1_beta2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use autoscaler1_beta2::AutoscalerHub; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.autoscalers().list("project", "zone") +//! .page_token("accusam") +//! .max_results(93) +//! .filter("justo") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your Google Compute Engine resources + Compute, + + /// View your Google Compute Engine resources + ComputeReadonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Compute => "https://www.googleapis.com/auth/compute", + Scope::ComputeReadonly => "https://www.googleapis.com/auth/compute.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::ComputeReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all AutoscalerHub related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// use autoscaler1_beta2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use autoscaler1_beta2::AutoscalerHub; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().list("project", "zone") +/// .page_token("labore") +/// .max_results(92) +/// .filter("nonumy") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct AutoscalerHub { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for AutoscalerHub {} + +impl<'a, C, NC, A> AutoscalerHub + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> AutoscalerHub { + AutoscalerHub { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn autoscalers(&'a self) -> AutoscalerMethods<'a, C, NC, A> { + AutoscalerMethods { hub: &self } + } + pub fn zone_operations(&'a self) -> ZoneOperationMethods<'a, C, NC, A> { + ZoneOperationMethods { hub: &self } + } + pub fn zones(&'a self) -> ZoneMethods<'a, C, NC, A> { + ZoneMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DeprecationStatus { + /// no description provided + pub deleted: String, + /// no description provided + pub deprecated: String, + /// no description provided + pub state: String, + /// no description provided + pub obsolete: String, + /// no description provided + pub replacement: String, +} + +impl Part for DeprecationStatus {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarningsData { + /// no description provided + pub key: String, + /// no description provided + pub value: String, +} + +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list zones](struct.ZoneListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Zone { + /// no description provided + pub status: Option, + /// Type of the resource. + pub kind: Option, + /// no description provided + pub description: Option, + /// no description provided + #[serde(alias="maintenanceWindows")] + pub maintenance_windows: Option>, + /// no description provided + pub deprecated: Option, + /// no description provided + pub region: Option, + /// no description provided + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// no description provided + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// no description provided + pub name: Option, +} + +impl Resource for Zone {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarnings { + /// no description provided + pub message: String, + /// no description provided + pub code: String, + /// no description provided + pub data: Vec, +} + +impl NestedType for OperationWarnings {} +impl Part for OperationWarnings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list zone operations](struct.ZoneOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationList { + /// no description provided + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// no description provided + pub items: Vec, + /// Type of resource. Always compute#operations for Operations resource. + pub kind: String, + /// no description provided + pub id: String, + /// no description provided + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for OperationList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ZoneMaintenanceWindows { + /// no description provided + #[serde(alias="endTime")] + pub end_time: String, + /// no description provided + pub description: String, + /// no description provided + #[serde(alias="beginTime")] + pub begin_time: String, + /// no description provided + pub name: String, +} + +impl NestedType for ZoneMaintenanceWindows {} +impl Part for ZoneMaintenanceWindows {} + + +/// Custom utilization metric policy. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AutoscalingPolicyCustomMetricUtilization { + /// Identifier of the metric. It should be a Cloud Monitoring metric. The metric can not have negative values. The metric should be an utilization metric (increasing number of VMs handling requests x times should reduce average value of the metric roughly x times). For example you could use: compute.googleapis.com/instance/network/received_bytes_count. + pub metric: String, + /// Defines type in which utilization_target is expressed. + #[serde(alias="utilizationTargetType")] + pub utilization_target_type: String, + /// Target value of the metric which Autoscaler should maintain. Must be a positive value. + #[serde(alias="utilizationTarget")] + pub utilization_target: f64, +} + +impl Part for AutoscalingPolicyCustomMetricUtilization {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationErrorErrors { + /// no description provided + pub message: String, + /// no description provided + pub code: String, + /// no description provided + pub location: String, +} + +impl NestedType for OperationErrorErrors {} +impl Part for OperationErrorErrors {} + + +/// Cloud Autoscaler policy. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AutoscalingPolicy { + /// Configuration parameters of autoscaling based on custom metric. + #[serde(alias="customMetricUtilizations")] + pub custom_metric_utilizations: Vec, + /// The maximum number of replicas that the Autoscaler can scale up to. + #[serde(alias="maxNumReplicas")] + pub max_num_replicas: i32, + /// Exactly one utilization policy should be provided. Configuration parameters of CPU based autoscaling policy. + #[serde(alias="cpuUtilization")] + pub cpu_utilization: AutoscalingPolicyCpuUtilization, + /// The minimum number of replicas that the Autoscaler can scale down to. + #[serde(alias="minNumReplicas")] + pub min_num_replicas: i32, + /// The number of seconds that the Autoscaler should wait between two succeeding changes to the number of virtual machines. You should define an interval that is at least as long as the initialization time of a virtual machine and the time it may take for replica pool to create the virtual machine. The default is 60 seconds. + #[serde(alias="coolDownPeriodSec")] + pub cool_down_period_sec: i32, + /// Configuration parameters of autoscaling based on load balancer. + #[serde(alias="loadBalancingUtilization")] + pub load_balancing_utilization: AutoscalingPolicyLoadBalancingUtilization, +} + +impl Part for AutoscalingPolicy {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationError { + /// no description provided + pub errors: Vec, +} + +impl NestedType for OperationError {} +impl Part for OperationError {} + + +/// CPU utilization policy. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AutoscalingPolicyCpuUtilization { + /// The target utilization that the Autoscaler should maintain. It is represented as a fraction of used cores. For example: 6 cores used in 8-core VM are represented here as 0.75. Must be a float value between (0, 1]. If not defined, the default is 0.8. + #[serde(alias="utilizationTarget")] + pub utilization_target: f64, +} + +impl Part for AutoscalingPolicyCpuUtilization {} + + +/// Load balancing utilization policy. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AutoscalingPolicyLoadBalancingUtilization { + /// Fraction of backend capacity utilization (set in HTTP load balancing configuration) that Autoscaler should maintain. Must be a positive float value. If not defined, the default is 0.8. For example if your maxRatePerInstance capacity (in HTTP Load Balancing configuration) is set at 10 and you would like to keep number of instances such that each instance receives 7 QPS on average, set this to 0.7. + #[serde(alias="utilizationTarget")] + pub utilization_target: f64, +} + +impl Part for AutoscalingPolicyLoadBalancingUtilization {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list autoscalers](struct.AutoscalerListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AutoscalerListResponse { + /// [Output only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Autoscaler resources. + pub items: Vec, + /// Type of resource. + pub kind: String, +} + +impl ResponseResult for AutoscalerListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update autoscalers](struct.AutoscalerUpdateCall.html) (response) +/// * [delete autoscalers](struct.AutoscalerDeleteCall.html) (response) +/// * [insert autoscalers](struct.AutoscalerInsertCall.html) (response) +/// * [get zone operations](struct.ZoneOperationGetCall.html) (response) +/// * [patch autoscalers](struct.AutoscalerPatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Operation { + /// no description provided + pub status: String, + /// no description provided + #[serde(alias="insertTime")] + pub insert_time: String, + /// no description provided + pub warnings: Vec, + /// no description provided + pub error: OperationError, + /// no description provided + #[serde(alias="targetId")] + pub target_id: String, + /// no description provided + #[serde(alias="targetLink")] + pub target_link: String, + /// no description provided + #[serde(alias="startTime")] + pub start_time: String, + /// no description provided + #[serde(alias="clientOperationId")] + pub client_operation_id: String, + /// no description provided + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// no description provided + pub id: String, + /// [Output Only] Type of the resource. Always kind#operation for Operation resources. + pub kind: String, + /// no description provided + pub name: String, + /// no description provided + pub zone: String, + /// no description provided + pub region: String, + /// no description provided + #[serde(alias="selfLink")] + pub self_link: String, + /// no description provided + #[serde(alias="operationType")] + pub operation_type: String, + /// no description provided + #[serde(alias="httpErrorMessage")] + pub http_error_message: String, + /// no description provided + pub progress: i32, + /// no description provided + #[serde(alias="endTime")] + pub end_time: String, + /// no description provided + #[serde(alias="httpErrorStatusCode")] + pub http_error_status_code: i32, + /// no description provided + #[serde(alias="statusMessage")] + pub status_message: String, + /// no description provided + pub user: String, +} + +impl ResponseResult for Operation {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list zones](struct.ZoneListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ZoneList { + /// no description provided + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// no description provided + pub items: Vec, + /// Type of resource. + pub kind: String, + /// no description provided + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ZoneList {} + + +/// Cloud Autoscaler resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list autoscalers](struct.AutoscalerListCall.html) (none) +/// * [update autoscalers](struct.AutoscalerUpdateCall.html) (request) +/// * [patch autoscalers](struct.AutoscalerPatchCall.html) (request) +/// * [delete autoscalers](struct.AutoscalerDeleteCall.html) (none) +/// * [insert autoscalers](struct.AutoscalerInsertCall.html) (request) +/// * [get autoscalers](struct.AutoscalerGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Autoscaler { + /// Type of resource. + pub kind: Option, + /// An optional textual description of the resource provided by the client. + pub description: Option, + /// Name of the Autoscaler resource. Must be unique per project and zone. + pub name: Option, + /// Configuration parameters for autoscaling algorithm. + #[serde(alias="autoscalingPolicy")] + pub autoscaling_policy: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] A self-link to the Autoscaler configuration resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// URL to the entity which will be autoscaled. Currently the only supported value is ReplicaPool?s URL. Note: it is illegal to specify multiple Autoscalers for the same target. + pub target: Option, +} + +impl RequestValue for Autoscaler {} +impl Resource for Autoscaler {} +impl ResponseResult for Autoscaler {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *zone* resources. +/// It is not used directly, but through the `AutoscalerHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use autoscaler1_beta2::AutoscalerHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.zones(); +/// # } +/// ``` +pub struct ZoneMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ZoneMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// + pub fn list(&self, project: &str) -> ZoneListCall<'a, C, NC, A> { + ZoneListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *zoneOperation* resources. +/// It is not used directly, but through the `AutoscalerHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use autoscaler1_beta2::AutoscalerHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.zone_operations(); +/// # } +/// ``` +pub struct ZoneOperationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ZoneOperationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of operation resources contained within the specified zone. + pub fn list(&self, project: &str, zone: &str) -> ZoneOperationListCall<'a, C, NC, A> { + ZoneOperationListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified zone-specific operation resource. + pub fn delete(&self, project: &str, zone: &str, operation: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + ZoneOperationDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the specified zone-specific operation resource. + pub fn get(&self, project: &str, zone: &str, operation: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + ZoneOperationGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *autoscaler* resources. +/// It is not used directly, but through the `AutoscalerHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use autoscaler1_beta2::AutoscalerHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.autoscalers(); +/// # } +/// ``` +pub struct AutoscalerMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AutoscalerMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all Autoscaler resources in this zone. + pub fn list(&self, project: &str, zone: &str) -> AutoscalerListCall<'a, C, NC, A> { + AutoscalerListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the Autoscaler resource. + pub fn update(&self, request: &Autoscaler, project: &str, zone: &str, autoscaler: &str) -> AutoscalerUpdateCall<'a, C, NC, A> { + AutoscalerUpdateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _autoscaler: autoscaler.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the Autoscaler resource. This method supports patch semantics. + pub fn patch(&self, request: &Autoscaler, project: &str, zone: &str, autoscaler: &str) -> AutoscalerPatchCall<'a, C, NC, A> { + AutoscalerPatchCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _autoscaler: autoscaler.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified Autoscaler resource. + pub fn delete(&self, project: &str, zone: &str, autoscaler: &str) -> AutoscalerDeleteCall<'a, C, NC, A> { + AutoscalerDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _autoscaler: autoscaler.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds new Autoscaler resource. + pub fn insert(&self, request: &Autoscaler, project: &str, zone: &str) -> AutoscalerInsertCall<'a, C, NC, A> { + AutoscalerInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the specified Autoscaler resource. + pub fn get(&self, project: &str, zone: &str, autoscaler: &str) -> AutoscalerGetCall<'a, C, NC, A> { + AutoscalerGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _autoscaler: autoscaler.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// +/// +/// A builder for the *list* method supported by a *zone* resource. +/// It is not used directly, but through a `ZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zones().list("project") +/// .page_token("gubergren") +/// .max_results(6) +/// .filter("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct ZoneListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ZoneList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.zones.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/{project}/zones".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ComputeReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + pub fn page_token(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + pub fn max_results(mut self, new_value: u32) -> ZoneListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + pub fn filter(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of operation resources contained within the specified zone. +/// +/// A builder for the *list* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().list("project", "zone") +/// .page_token("justo") +/// .max_results(80) +/// .filter("et") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.zoneOperations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/{project}/zones/{zone}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ComputeReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn zone(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + pub fn page_token(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + pub fn max_results(mut self, new_value: u32) -> ZoneOperationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + pub fn filter(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified zone-specific operation resource. +/// +/// A builder for the *delete* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().delete("project", "zone", "operation") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.zoneOperations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["project", "zone", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/{project}/zones/{zone}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Compute.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn zone(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn operation(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the specified zone-specific operation resource. +/// +/// A builder for the *get* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().get("project", "zone", "operation") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.zoneOperations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["alt", "project", "zone", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/{project}/zones/{zone}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ComputeReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn zone(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn operation(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all Autoscaler resources in this zone. +/// +/// A builder for the *list* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().list("project", "zone") +/// .page_token("Lorem") +/// .max_results(26) +/// .filter("erat") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AutoscalerListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ComputeReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + pub fn page_token(mut self, new_value: &str) -> AutoscalerListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + pub fn max_results(mut self, new_value: u32) -> AutoscalerListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + pub fn filter(mut self, new_value: &str) -> AutoscalerListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the Autoscaler resource. +/// +/// A builder for the *update* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// use autoscaler1_beta2::Autoscaler; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Autoscaler = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().update(&req, "project", "zone", "autoscaler") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _request: Autoscaler, + _project: String, + _zone: String, + _autoscaler: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("autoscaler", self._autoscaler.to_string())); + for &field in ["alt", "project", "zone", "autoscaler"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers/{autoscaler}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Compute.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{autoscaler}", "autoscaler")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "autoscaler"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Autoscaler) -> AutoscalerUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerUpdateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerUpdateCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *autoscaler* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the Autoscaler resource. + pub fn autoscaler(mut self, new_value: &str) -> AutoscalerUpdateCall<'a, C, NC, A> { + self._autoscaler = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the Autoscaler resource. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// use autoscaler1_beta2::Autoscaler; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Autoscaler = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().patch(&req, "project", "zone", "autoscaler") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _request: Autoscaler, + _project: String, + _zone: String, + _autoscaler: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("autoscaler", self._autoscaler.to_string())); + for &field in ["alt", "project", "zone", "autoscaler"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers/{autoscaler}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Compute.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{autoscaler}", "autoscaler")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "autoscaler"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Autoscaler) -> AutoscalerPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerPatchCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerPatchCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *autoscaler* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the Autoscaler resource. + pub fn autoscaler(mut self, new_value: &str) -> AutoscalerPatchCall<'a, C, NC, A> { + self._autoscaler = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified Autoscaler resource. +/// +/// A builder for the *delete* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().delete("project", "zone", "autoscaler") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _autoscaler: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("autoscaler", self._autoscaler.to_string())); + for &field in ["alt", "project", "zone", "autoscaler"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers/{autoscaler}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Compute.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{autoscaler}", "autoscaler")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "autoscaler"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *autoscaler* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the Autoscaler resource. + pub fn autoscaler(mut self, new_value: &str) -> AutoscalerDeleteCall<'a, C, NC, A> { + self._autoscaler = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds new Autoscaler resource. +/// +/// A builder for the *insert* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// use autoscaler1_beta2::Autoscaler; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Autoscaler = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().insert(&req, "project", "zone") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _request: Autoscaler, + _project: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + for &field in ["alt", "project", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Compute.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Autoscaler) -> AutoscalerInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerInsertCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the specified Autoscaler resource. +/// +/// A builder for the *get* method supported by a *autoscaler* resource. +/// It is not used directly, but through a `AutoscalerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-autoscaler1_beta2" as autoscaler1_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use autoscaler1_beta2::AutoscalerHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = AutoscalerHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.autoscalers().get("project", "zone", "autoscaler") +/// .doit(); +/// # } +/// ``` +pub struct AutoscalerGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a AutoscalerHub, + _project: String, + _zone: String, + _autoscaler: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AutoscalerGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AutoscalerGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Autoscaler)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "autoscaler.autoscalers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("autoscaler", self._autoscaler.to_string())); + for &field in ["alt", "project", "zone", "autoscaler"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/autoscaler/v1beta2/projects/{project}/zones/{zone}/autoscalers/{autoscaler}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ComputeReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{autoscaler}", "autoscaler")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "autoscaler"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of Autoscaler resource. + pub fn project(mut self, new_value: &str) -> AutoscalerGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Zone name of Autoscaler resource. + pub fn zone(mut self, new_value: &str) -> AutoscalerGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *autoscaler* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the Autoscaler resource. + pub fn autoscaler(mut self, new_value: &str) -> AutoscalerGetCall<'a, C, NC, A> { + self._autoscaler = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AutoscalerGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AutoscalerGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AutoscalerGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/bigquery2/Cargo.toml b/gen/bigquery2/Cargo.toml new file mode 100644 index 0000000000..4494055158 --- /dev/null +++ b/gen/bigquery2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-bigquery2" +version = "0.1.0+20141112" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with bigquery (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/bigquery2" +homepage = "https://developers.google.com/bigquery/docs/overview" +documentation = "http://byron.github.io/google-apis-rs/google-bigquery2" +license = "MIT" +keywords = ["bigquery", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/bigquery2/LICENSE.md b/gen/bigquery2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/bigquery2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/bigquery2/README.md b/gen/bigquery2/README.md new file mode 100644 index 0000000000..88fae61284 --- /dev/null +++ b/gen/bigquery2/README.md @@ -0,0 +1,186 @@ + +The `google-bigquery2` library allows access to all features of the *Google bigquery* service. + +This documentation was generated from *bigquery* crate version *0.1.0+20141112*, where *20141112* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *bigquery* *v2* API can be found at the +[official documentation site](https://developers.google.com/bigquery/docs/overview). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-bigquery2/struct.Bigquery.html) ... + +* [datasets](http://byron.github.io/google-apis-rs/google-bigquery2/struct.Dataset.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.DatasetUpdateCall.html) +* [jobs](http://byron.github.io/google-apis-rs/google-bigquery2/struct.Job.html) + * [*get*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobGetCall.html), [*get query results*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobGetQueryResultCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobListCall.html) and [*query*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobQueryCall.html) +* projects + * [*list*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.ProjectListCall.html) +* tabledata + * [*insert all*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TabledataInsertAllCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TabledataListCall.html) +* [tables](http://byron.github.io/google-apis-rs/google-bigquery2/struct.Table.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TableDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TableGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TableInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TableListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TablePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.TableUpdateCall.html) + + +Upload supported by ... + +* [*insert jobs*](http://byron.github.io/google-apis-rs/google-bigquery2/struct.JobInsertCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-bigquery2/struct.Bigquery.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-bigquery2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.tables().update(...).doit() +let r = hub.tables().insert(...).doit() +let r = hub.tables().list(...).doit() +let r = hub.tables().delete(...).doit() +let r = hub.tables().get(...).doit() +let r = hub.tables().patch(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-bigquery2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-bigquery2" as bigquery2; +use bigquery2::Table; +use bigquery2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use bigquery2::Bigquery; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Bigquery::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Table = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.tables().update(&req, "projectId", "datasetId", "tableId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-bigquery2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-bigquery2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-bigquery2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-bigquery2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-bigquery2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-bigquery2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-bigquery2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-bigquery2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-bigquery2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-bigquery2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **bigquery2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/bigquery2/src/cmn.rs b/gen/bigquery2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/bigquery2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/bigquery2/src/lib.rs b/gen/bigquery2/src/lib.rs new file mode 100644 index 0000000000..f262b8d91c --- /dev/null +++ b/gen/bigquery2/src/lib.rs @@ -0,0 +1,7426 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *bigquery* crate version *0.1.0+20141112*, where *20141112* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *bigquery* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/bigquery/docs/overview). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/bigquery2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Bigquery.html) ... +//! +//! * [datasets](struct.Dataset.html) +//! * [*delete*](struct.DatasetDeleteCall.html), [*get*](struct.DatasetGetCall.html), [*insert*](struct.DatasetInsertCall.html), [*list*](struct.DatasetListCall.html), [*patch*](struct.DatasetPatchCall.html) and [*update*](struct.DatasetUpdateCall.html) +//! * [jobs](struct.Job.html) +//! * [*get*](struct.JobGetCall.html), [*get query results*](struct.JobGetQueryResultCall.html), [*insert*](struct.JobInsertCall.html), [*list*](struct.JobListCall.html) and [*query*](struct.JobQueryCall.html) +//! * projects +//! * [*list*](struct.ProjectListCall.html) +//! * tabledata +//! * [*insert all*](struct.TabledataInsertAllCall.html) and [*list*](struct.TabledataListCall.html) +//! * [tables](struct.Table.html) +//! * [*delete*](struct.TableDeleteCall.html), [*get*](struct.TableGetCall.html), [*insert*](struct.TableInsertCall.html), [*list*](struct.TableListCall.html), [*patch*](struct.TablePatchCall.html) and [*update*](struct.TableUpdateCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*insert jobs*](struct.JobInsertCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Bigquery.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.tables().update(...).doit() +//! let r = hub.tables().insert(...).doit() +//! let r = hub.tables().list(...).doit() +//! let r = hub.tables().delete(...).doit() +//! let r = hub.tables().get(...).doit() +//! let r = hub.tables().patch(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-bigquery2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-bigquery2" as bigquery2; +//! use bigquery2::Table; +//! use bigquery2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use bigquery2::Bigquery; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Bigquery::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Table = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.tables().update(&req, "projectId", "datasetId", "tableId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your data and permissions in Google Cloud Storage + DevstorageFullControl, + + /// View your data in Google Cloud Storage + DevstorageReadOnly, + + /// Manage your data in Google Cloud Storage + DevstorageReadWrite, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, + + /// Insert data into Google BigQuery + Insertdata, + + /// View and manage your data in Google BigQuery + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::DevstorageFullControl => "https://www.googleapis.com/auth/devstorage.full_control", + Scope::DevstorageReadOnly => "https://www.googleapis.com/auth/devstorage.read_only", + Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::Insertdata => "https://www.googleapis.com/auth/bigquery.insertdata", + Scope::Full => "https://www.googleapis.com/auth/bigquery", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Bigquery related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Table; +/// use bigquery2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Table = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().update(&req, "projectId", "datasetId", "tableId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Bigquery { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Bigquery {} + +impl<'a, C, NC, A> Bigquery + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Bigquery { + Bigquery { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn datasets(&'a self) -> DatasetMethods<'a, C, NC, A> { + DatasetMethods { hub: &self } + } + pub fn jobs(&'a self) -> JobMethods<'a, C, NC, A> { + JobMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, NC, A> { + ProjectMethods { hub: &self } + } + pub fn tabledata(&'a self) -> TabledataMethods<'a, C, NC, A> { + TabledataMethods { hub: &self } + } + pub fn tables(&'a self) -> TableMethods<'a, C, NC, A> { + TableMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// The rows to insert. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TableDataInsertAllRequestRows { + /// [Optional] A unique ID for each row. BigQuery uses this property to detect duplicate insertion requests on a best-effort basis. + #[serde(alias="insertId")] + pub insert_id: String, + /// [Required] A JSON object that contains a row of data. The object's properties and values must match the destination table's schema. + pub json: JsonObject, +} + +impl NestedType for TableDataInsertAllRequestRows {} +impl Part for TableDataInsertAllRequestRows {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobStatistics4 { + /// [Experimental] Number of files per destination URI or URI pattern specified in the extract configuration. These values will be in the same order as the URIs specified in the 'destinationUris' field. + #[serde(alias="destinationUriFileCounts")] + pub destination_uri_file_counts: Vec, +} + +impl Part for JobStatistics4 {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query jobs](struct.JobQueryCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct QueryRequest { + /// [Optional] How long to wait for the query to complete, in milliseconds, before the request times out and returns. Note that this is only a timeout for the request, not the query. If the query takes longer to run than the timeout value, the call returns without any results and with the 'jobComplete' flag set to false. You can call GetQueryResults() to wait for the query to complete and read the results. The default value is 10000 milliseconds (10 seconds). + #[serde(alias="timeoutMs")] + pub timeout_ms: Option, + /// The resource type of the request. + pub kind: Option, + /// [Optional] If set, don't actually run this job. A valid query will return a mostly empty response with some processing statistics, while an invalid query will return the same error it would if it wasn't a dry run. + #[serde(alias="dryRun")] + pub dry_run: Option, + /// [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. The default value is true. + #[serde(alias="useQueryCache")] + pub use_query_cache: Option, + /// [Optional] Specifies the default datasetId and projectId to assume for any unqualified table names in the query. If not set, all table names in the query string must be qualified in the format 'datasetId.tableId'. + #[serde(alias="defaultDataset")] + pub default_dataset: Option, + /// [Optional] The maximum number of rows of data to return per page of results. Setting this flag to a small value such as 1000 and then paging through results might improve reliability when the query result set is large. In addition to this limit, responses are also limited to 10 MB. By default, there is no maximum row count, and only the byte limit applies. + #[serde(alias="maxResults")] + pub max_results: Option, + /// [Required] A query string, following the BigQuery query syntax, of the query to execute. Example: "SELECT count(f1) FROM [myProjectId:myDatasetId.myTableId]". + pub query: Option, + /// [Deprecated] This property is deprecated. + #[serde(alias="preserveNulls")] + pub preserve_nulls: Option, +} + +impl RequestValue for QueryRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobStatistics2 { + /// [Output-only] Whether the query result was fetched from the query cache. + #[serde(alias="cacheHit")] + pub cache_hit: bool, + /// [Output-only] Total bytes processed for this job. + #[serde(alias="totalBytesProcessed")] + pub total_bytes_processed: String, +} + +impl Part for JobStatistics2 {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobStatistics3 { + /// [Output-only] Number of rows imported in a load job. Note that while an import job is in the running state, this value may change. + #[serde(alias="outputRows")] + pub output_rows: String, + /// [Output-only] Number of source files in a load job. + #[serde(alias="inputFiles")] + pub input_files: String, + /// [Output-only] Number of bytes of source data in a joad job. + #[serde(alias="inputFileBytes")] + pub input_file_bytes: String, + /// [Output-only] Size of the loaded data in bytes. Note that while an import job is in the running state, this value may change. + #[serde(alias="outputBytes")] + pub output_bytes: String, +} + +impl Part for JobStatistics3 {} + + +/// Represents a single JSON object. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct JsonObject(HashMap); + +impl Part for JsonObject {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list projects](struct.ProjectListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProjectList { + /// A token to request the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The total number of projects in the list. + #[serde(alias="totalItems")] + pub total_items: i32, + /// The type of list. + pub kind: String, + /// A hash of the page of results + pub etag: String, + /// Projects to which you have at least READ access. + pub projects: Vec, +} + +impl ResponseResult for ProjectList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TableFieldSchema { + /// [Optional] Describes the nested schema fields if the type property is set to RECORD. + pub fields: Vec, + /// [Optional] The field description. The maximum length is 16K characters. + pub description: String, + /// [Required] The field data type. Possible values include STRING, INTEGER, FLOAT, BOOLEAN, TIMESTAMP or RECORD (where RECORD indicates that the field contains a nested schema). + #[serde(alias="type")] + pub type_: String, + /// [Optional] The field mode. Possible values include NULLABLE, REQUIRED and REPEATED. The default value is NULLABLE. + pub mode: String, + /// [Required] The field name. The name must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_), and must start with a letter or underscore. The maximum length is 128 characters. + pub name: String, +} + +impl Part for TableFieldSchema {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get datasets](struct.DatasetGetCall.html) (response) +/// * [list datasets](struct.DatasetListCall.html) (none) +/// * [patch datasets](struct.DatasetPatchCall.html) (request|response) +/// * [update datasets](struct.DatasetUpdateCall.html) (request|response) +/// * [delete datasets](struct.DatasetDeleteCall.html) (none) +/// * [insert datasets](struct.DatasetInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Dataset { + /// [Output-only] The resource type. + pub kind: Option, + /// [Optional] A user-friendly description of the dataset. + pub description: Option, + /// [Required] A reference that identifies the dataset. + #[serde(alias="datasetReference")] + pub dataset_reference: Option, + /// [Output-only] The time when this dataset was created, in milliseconds since the epoch. + #[serde(alias="creationTime")] + pub creation_time: Option, + /// [Optional] An array of objects that define dataset access for one or more entities. You can set this property when inserting or updating a dataset in order to control who is allowed to access the data. If unspecified at dataset creation time, BigQuery adds default dataset access for the following entities: access.specialGroup: projectReaders; access.role: READER; access.specialGroup: projectWriters; access.role: WRITER; access.specialGroup: projectOwners; access.role: OWNER; access.userByEmail: [dataset creator email]; access.role: OWNER; + pub access: Option>, + /// [Output-only] A hash of the resource. + pub etag: Option, + /// [Optional] A descriptive name for the dataset. + #[serde(alias="friendlyName")] + pub friendly_name: Option, + /// [Output-only] The date when this dataset or any of its tables was last modified, in milliseconds since the epoch. + #[serde(alias="lastModifiedTime")] + pub last_modified_time: Option, + /// [Output-only] The fully-qualified unique name of the dataset in the format projectId:datasetId. The dataset name without the project name is given in the datasetId field. When creating a new dataset, leave this field blank, and instead specify the datasetId field. + pub id: Option, + /// [Output-only] A URL that can be used to access the resource again. You can use this URL in Get or Update requests to the resource. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Dataset {} +impl Resource for Dataset {} +impl ResponseResult for Dataset {} + + +/// An array of errors for rows that were not inserted. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableDataInsertAllResponseInsertErrors { + /// The index of the row that error applies to. + pub index: u32, + /// Error information for the row indicated by the index property. + pub errors: Vec, +} + +impl NestedType for TableDataInsertAllResponseInsertErrors {} +impl Part for TableDataInsertAllResponseInsertErrors {} + + +/// Represents a single cell in the result set. Users of the java client can detect whether their value result is null by calling 'com.google.api.client.util.Data.isNull(cell.getV())'. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableCell { + /// no description provided + pub v: String, +} + +impl Part for TableCell {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobReference { + /// [Required] The ID of the project containing this job. + #[serde(alias="projectId")] + pub project_id: String, + /// [Required] The ID of the job. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 characters. + #[serde(alias="jobId")] + pub job_id: String, +} + +impl Part for JobReference {} + + +/// An array of the dataset resources in the project. Each resource contains basic information. For full information about a particular dataset resource, use the Datasets: get method. This property is omitted when there are no datasets in the project. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatasetListDatasets { + /// A descriptive name for the dataset, if one exists. + #[serde(alias="friendlyName")] + pub friendly_name: String, + /// The resource type. This property always returns the value "bigquery#dataset". + pub kind: String, + /// The fully-qualified, unique, opaque ID of the dataset. + pub id: String, + /// The dataset reference. Use this property to access specific parts of the dataset's ID, such as project ID or dataset ID. + #[serde(alias="datasetReference")] + pub dataset_reference: DatasetReference, +} + +impl NestedType for DatasetListDatasets {} +impl Part for DatasetListDatasets {} + + +/// Tables in the requested dataset. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableListTables { + /// The user-friendly name for this table. + #[serde(alias="friendlyName")] + pub friendly_name: String, + /// The resource type. + pub kind: String, + /// The type of table. Possible values are: TABLE, VIEW. + #[serde(alias="type")] + pub type_: String, + /// An opaque ID of the table + pub id: String, + /// A reference uniquely identifying the table. + #[serde(alias="tableReference")] + pub table_reference: TableReference, +} + +impl NestedType for TableListTables {} +impl Part for TableListTables {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list tables](struct.TableListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableList { + /// A token to request the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Tables in the requested dataset. + pub tables: Vec, + /// The type of list. + pub kind: String, + /// A hash of this page of results. + pub etag: String, + /// The total number of tables in the dataset. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for TableList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProjectReference { + /// [Required] ID of the project. Can be either the numeric ID or the assigned ID of the project. + #[serde(alias="projectId")] + pub project_id: String, +} + +impl Part for ProjectReference {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list tabledata](struct.TabledataListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableDataList { + /// A token used for paging results. Providing this token instead of the startIndex parameter can help you retrieve stable results when an underlying table is changing. + #[serde(alias="pageToken")] + pub page_token: String, + /// The resource type of the response. + pub kind: String, + /// A hash of this page of results. + pub etag: String, + /// Rows of results. + pub rows: Vec, + /// The total number of rows in the complete table. + #[serde(alias="totalRows")] + pub total_rows: String, +} + +impl ResponseResult for TableDataList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert jobs](struct.JobInsertCall.html) (request|response) +/// * [query jobs](struct.JobQueryCall.html) (none) +/// * [list jobs](struct.JobListCall.html) (none) +/// * [get query results jobs](struct.JobGetQueryResultCall.html) (none) +/// * [get jobs](struct.JobGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Job { + /// [Output-only] The status of this job. Examine this value when polling an asynchronous job to see if the job is complete. + pub status: Option, + /// [Output-only] The type of the resource. + pub kind: Option, + /// [Output-only] Information about the job, including starting time and ending time of the job. + pub statistics: Option, + /// [Optional] Reference describing the unique-per-user name of the job. + #[serde(alias="jobReference")] + pub job_reference: Option, + /// [Output-only] A hash of this resource. + pub etag: Option, + /// [Output-only] A URL that can be used to access this resource again. + #[serde(alias="selfLink")] + pub self_link: Option, + /// [Required] Describes the job configuration. + pub configuration: Option, + /// [Output-only] Opaque ID field of the job + pub id: Option, + /// [Output-only] Email address of the user who ran the job. + pub user_email: Option, +} + +impl RequestValue for Job {} +impl Resource for Job {} +impl ResponseResult for Job {} + + +/// List of jobs that were requested. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct JobListJobs { + /// [Full-projection-only] Describes the state of the job. + pub status: JobStatus, + /// The resource type. + pub kind: String, + /// [Output-only] Information about the job, including starting time and ending time of the job. + pub statistics: JobStatistics, + /// Job reference uniquely identifying the job. + #[serde(alias="jobReference")] + pub job_reference: JobReference, + /// Running state of the job. When the state is DONE, errorResult can be checked to determine whether the job succeeded or failed. + pub state: String, + /// A result object that will be present only if the job has failed. + #[serde(alias="errorResult")] + pub error_result: ErrorProto, + /// [Full-projection-only] Specifies the job configuration. + pub configuration: JobConfiguration, + /// Unique opaque ID of the job. + pub id: String, + /// [Full-projection-only] Email address of the user who ran the job. + pub user_email: String, +} + +impl NestedType for JobListJobs {} +impl Part for JobListJobs {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfigurationLoad { + /// [Optional] The character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split using the values of the quote and fieldDelimiter properties. + pub encoding: String, + /// [Optional] The value that is used to quote data sections in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. The default value is a double-quote ('"'). If your data does not contain quoted sections, set the property value to an empty string. If your data contains quoted newline characters, you must also set the allowQuotedNewlines property to true. + pub quote: String, + /// [Required] The destination table to load the data into. + #[serde(alias="destinationTable")] + pub destination_table: TableReference, + /// [Required] The fully-qualified URIs that point to your data in Google Cloud Storage. Wildcard names are only supported when they appear at the end of the URI. + #[serde(alias="sourceUris")] + pub source_uris: Vec, + /// Indicates if BigQuery should allow quoted data sections that contain newline characters in a CSV file. The default value is false. + #[serde(alias="allowQuotedNewlines")] + pub allow_quoted_newlines: bool, + /// [Experimental] Names(case-sensitive) of properties to keep when importing data. If this is populated, only the specified properties will be imported for each entity. Currently, this is only supported for DATASTORE_BACKUP imports and only top level properties are supported. If any specified property is not found in the Datastore 'Kind' being imported, that is an error. Note: This feature is experimental and can change in the future. + #[serde(alias="projectionFields")] + pub projection_fields: Vec, + /// [Optional] Accept rows that are missing trailing optional columns. The missing values are treated as nulls. Default is false which treats short rows as errors. Only applicable to CSV, ignored for other formats. + #[serde(alias="allowJaggedRows")] + pub allow_jagged_rows: bool, + /// [Optional] The separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split the data in its raw, binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. The default value is a comma (','). + #[serde(alias="fieldDelimiter")] + pub field_delimiter: String, + /// [Optional] The format of the data files. For CSV files, specify "CSV". For datastore backups, specify "DATASTORE_BACKUP". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". The default value is CSV. + #[serde(alias="sourceFormat")] + pub source_format: String, + /// [Optional] The maximum number of bad records that BigQuery can ignore when running the job. If the number of bad records exceeds this value, an 'invalid' error is returned in the job result and the job fails. The default value is 0, which requires that all records are valid. + #[serde(alias="maxBadRecords")] + pub max_bad_records: i32, + /// [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false which treats unknown values as errors. For CSV this ignores extra values at the end of a line. For JSON this ignores named values that do not match any column name. + #[serde(alias="ignoreUnknownValues")] + pub ignore_unknown_values: bool, + /// [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="writeDisposition")] + pub write_disposition: String, + /// [Optional] The number of rows at the top of a CSV file that BigQuery will skip when loading the data. The default value is 0. This property is useful if you have header rows in the file that should be skipped. + #[serde(alias="skipLeadingRows")] + pub skip_leading_rows: i32, + /// [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="createDisposition")] + pub create_disposition: String, + /// [Deprecated] The format of the schemaInline property. + #[serde(alias="schemaInlineFormat")] + pub schema_inline_format: String, + /// [Deprecated] The inline schema. For CSV schemas, specify as "Field1:Type1[,Field2:Type2]*". For example, "foo:STRING, bar:INTEGER, baz:FLOAT". + #[serde(alias="schemaInline")] + pub schema_inline: String, + /// [Optional] The schema for the destination table. The schema can be omitted if the destination table already exists or if the schema can be inferred from the loaded data. + pub schema: TableSchema, +} + +impl Part for JobConfigurationLoad {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list jobs](struct.JobListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct JobList { + /// A token to request the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Total number of jobs in this collection. + #[serde(alias="totalItems")] + pub total_items: i32, + /// The resource type of the response. + pub kind: String, + /// A hash of this page of results. + pub etag: String, + /// List of jobs that were requested. + pub jobs: Vec, +} + +impl ResponseResult for JobList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfigurationExtract { + /// [Pick one] DEPRECATED: Use destinationUris instead, passing only one URI as necessary. The fully-qualified Google Cloud Storage URI where the extracted table should be written. + #[serde(alias="destinationUri")] + pub destination_uri: String, + /// [Optional] The exported file format. Possible values include CSV, NEWLINE_DELIMITED_JSON and AVRO. The default value is CSV. Tables with nested or repeated fields cannot be exported as CSV. + #[serde(alias="destinationFormat")] + pub destination_format: String, + /// [Optional] The compression type to use for exported files. Possible values include GZIP and NONE. The default value is NONE. + pub compression: String, + /// [Pick one] A list of fully-qualified Google Cloud Storage URIs where the extracted table should be written. + #[serde(alias="destinationUris")] + pub destination_uris: Vec, + /// [Optional] Whether to print out a header row in the results. Default is true. + #[serde(alias="printHeader")] + pub print_header: bool, + /// [Optional] Delimiter to use between fields in the exported data. Default is ',' + #[serde(alias="fieldDelimiter")] + pub field_delimiter: String, + /// [Required] A reference to the table being exported. + #[serde(alias="sourceTable")] + pub source_table: TableReference, +} + +impl Part for JobConfigurationExtract {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get query results jobs](struct.JobGetQueryResultCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct GetQueryResultsResponse { + /// The resource type of the response. + pub kind: String, + /// An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. Present only when the query completes successfully. + pub rows: Vec, + /// Reference to the BigQuery Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). + #[serde(alias="jobReference")] + pub job_reference: JobReference, + /// Whether the query result was fetched from the query cache. + #[serde(alias="cacheHit")] + pub cache_hit: bool, + /// Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. + #[serde(alias="jobComplete")] + pub job_complete: bool, + /// The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. Present only when the query completes successfully. + #[serde(alias="totalRows")] + pub total_rows: String, + /// The total number of bytes processed for this query. + #[serde(alias="totalBytesProcessed")] + pub total_bytes_processed: String, + /// A token used for paging results. + #[serde(alias="pageToken")] + pub page_token: String, + /// A hash of this response. + pub etag: String, + /// The schema of the results. Present only when the query completes successfully. + pub schema: TableSchema, +} + +impl ResponseResult for GetQueryResultsResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ErrorProto { + /// Debugging information. This property is internal to Google and should not be used. + #[serde(alias="debugInfo")] + pub debug_info: String, + /// A human-readable description of the error. + pub message: String, + /// A short error code that summarizes the error. + pub reason: String, + /// Specifies where the error occurred, if present. + pub location: String, +} + +impl Part for ErrorProto {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfigurationLink { + /// [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="createDisposition")] + pub create_disposition: String, + /// [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="writeDisposition")] + pub write_disposition: String, + /// [Required] The destination table of the link job. + #[serde(alias="destinationTable")] + pub destination_table: TableReference, + /// [Required] URI of source table to link. + #[serde(alias="sourceUri")] + pub source_uri: Vec, +} + +impl Part for JobConfigurationLink {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ViewDefinition { + /// [Required] A query that BigQuery executes when the view is referenced. + pub query: String, +} + +impl Part for ViewDefinition {} + + +/// [Optional] An array of objects that define dataset access for one or more entities. You can set this property when inserting or updating a dataset in order to control who is allowed to access the data. If unspecified at dataset creation time, BigQuery adds default dataset access for the following entities: access.specialGroup: projectReaders; access.role: READER; access.specialGroup: projectWriters; access.role: WRITER; access.specialGroup: projectOwners; access.role: OWNER; access.userByEmail: [dataset creator email]; access.role: OWNER; +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatasetAccess { + /// [Pick one] A domain to grant access to. Any users signed in with the domain specified will be granted the specified access. Example: "example.com". + pub domain: String, + /// [Required] Describes the rights granted to the user specified by the other member of the access object. The following string values are supported: READER, WRITER, OWNER. + pub role: String, + /// [Pick one] An email address of a user to grant access to. For example: fred@example.com. + #[serde(alias="userByEmail")] + pub user_by_email: String, + /// [Pick one] A special group to grant access to. Possible values include: projectOwners: Owners of the enclosing project. projectReaders: Readers of the enclosing project. projectWriters: Writers of the enclosing project. allAuthenticatedUsers: All authenticated BigQuery users. + #[serde(alias="specialGroup")] + pub special_group: String, + /// [Pick one] An email address of a Google Group to grant access to. + #[serde(alias="groupByEmail")] + pub group_by_email: String, + /// [Pick one] A view from a different dataset to grant access to. Queries executed against that view will have read access to tables in this dataset. The role field is not required when this field is set. If that view is updated by any user, access to the view needs to be granted again via an update operation. + pub view: TableReference, +} + +impl NestedType for DatasetAccess {} +impl Part for DatasetAccess {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobStatus { + /// [Output-only] Running state of the job. + pub state: String, + /// [Output-only] All errors encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful. + pub errors: Vec, + /// [Output-only] Final error result of the job. If present, indicates that the job has completed and was unsuccessful. + #[serde(alias="errorResult")] + pub error_result: ErrorProto, +} + +impl Part for JobStatus {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TableSchema { + /// Describes the fields in a table. + pub fields: Vec, +} + +impl Part for TableSchema {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +/// The contained type is `Option`. +/// +#[derive(Clone, Debug, Serialize)] +pub struct JsonValue(json::Value); + +impl Default for JsonValue { + fn default() -> JsonValue { + JsonValue(json::Value::Null) + } +} + +impl Part for JsonValue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert all tabledata](struct.TabledataInsertAllCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TableDataInsertAllRequest { + /// [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors. + #[serde(alias="ignoreUnknownValues")] + pub ignore_unknown_values: Option, + /// The resource type of the response. + pub kind: Option, + /// The rows to insert. + pub rows: Option>, + /// [Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist. + #[serde(alias="skipInvalidRows")] + pub skip_invalid_rows: Option, +} + +impl RequestValue for TableDataInsertAllRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list datasets](struct.DatasetListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatasetList { + /// A token that can be used to request the next results page. This property is omitted on the final results page. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The list type. This property always returns the value "bigquery#datasetList". + pub kind: String, + /// An array of the dataset resources in the project. Each resource contains basic information. For full information about a particular dataset resource, use the Datasets: get method. This property is omitted when there are no datasets in the project. + pub datasets: Vec, + /// A hash value of the results page. You can use this property to determine if the page has changed since the last request. + pub etag: String, +} + +impl ResponseResult for DatasetList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobStatistics { + /// [Output-only] Statistics for a load job. + pub load: JobStatistics3, + /// [Output-only] Statistics for an extract job. + pub extract: JobStatistics4, + /// [Output-only] Start time of this job, in milliseconds since the epoch. This field will be present when the job transitions from the PENDING state to either RUNNING or DONE. + #[serde(alias="startTime")] + pub start_time: String, + /// [Output-only] Statistics for a query job. + pub query: JobStatistics2, + /// [Output-only] End time of this job, in milliseconds since the epoch. This field will be present whenever a job is in the DONE state. + #[serde(alias="endTime")] + pub end_time: String, + /// [Output-only] Creation time of this job, in milliseconds since the epoch. This field will be present on all jobs. + #[serde(alias="creationTime")] + pub creation_time: String, + /// [Output-only] [Deprecated] Use the bytes processed in the query statistics instead. + #[serde(alias="totalBytesProcessed")] + pub total_bytes_processed: String, +} + +impl Part for JobStatistics {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfigurationQuery { + /// [Experimental] Flattens all nested and repeated fields in the query results. The default value is true. allowLargeResults must be true if this is set to false. + #[serde(alias="flattenResults")] + pub flatten_results: bool, + /// [Optional] Whether to look for the result in the query cache. The query cache is a best-effort cache that will be flushed whenever tables in the query are modified. Moreover, the query cache is only available when a query does not have a destination table specified. + #[serde(alias="useQueryCache")] + pub use_query_cache: bool, + /// [Optional] Specifies the default dataset to use for unqualified table names in the query. + #[serde(alias="defaultDataset")] + pub default_dataset: DatasetReference, + /// [Optional] Describes the table where the query results should be stored. If not present, a new table will be created to store the results. + #[serde(alias="destinationTable")] + pub destination_table: TableReference, + /// [Optional] Specifies a priority for the query. Possible values include INTERACTIVE and BATCH. The default value is INTERACTIVE. + pub priority: String, + /// [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="writeDisposition")] + pub write_disposition: String, + /// If true, allows the query to produce arbitrarily large result tables at a slight cost in performance. Requires destinationTable to be set. + #[serde(alias="allowLargeResults")] + pub allow_large_results: bool, + /// [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="createDisposition")] + pub create_disposition: String, + /// [Required] BigQuery SQL query to execute. + pub query: String, + /// [Deprecated] This property is deprecated. + #[serde(alias="preserveNulls")] + pub preserve_nulls: bool, +} + +impl Part for JobConfigurationQuery {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatasetReference { + /// [Optional] The ID of the project containing this dataset. + #[serde(alias="projectId")] + pub project_id: String, + /// [Required] A unique ID for this dataset, without the project name. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + #[serde(alias="datasetId")] + pub dataset_id: String, +} + +impl Part for DatasetReference {} + + +/// Represents a single row in the result set, consisting of one or more fields. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableRow { + /// no description provided + pub f: Vec, +} + +impl Part for TableRow {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfiguration { + /// [Pick one] Configures a load job. + pub load: JobConfigurationLoad, + /// [Optional] If set, don't actually run this job. A valid query will return a mostly empty response with some processing statistics, while an invalid query will return the same error it would if it wasn't a dry run. Behavior of non-query jobs is undefined. + #[serde(alias="dryRun")] + pub dry_run: bool, + /// [Pick one] Configures a query job. + pub query: JobConfigurationQuery, + /// [Pick one] Configures a link job. + pub link: JobConfigurationLink, + /// [Pick one] Copies a table. + pub copy: JobConfigurationTableCopy, + /// [Pick one] Configures an extract job. + pub extract: JobConfigurationExtract, +} + +impl Part for JobConfiguration {} + + +/// Projects to which you have at least READ access. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProjectListProjects { + /// A descriptive name for this project. + #[serde(alias="friendlyName")] + pub friendly_name: String, + /// The resource type. + pub kind: String, + /// The numeric ID of this project. + #[serde(alias="numericId")] + pub numeric_id: String, + /// An opaque ID of this project. + pub id: String, + /// A unique reference to this project. + #[serde(alias="projectReference")] + pub project_reference: ProjectReference, +} + +impl NestedType for ProjectListProjects {} +impl Part for ProjectListProjects {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TableReference { + /// [Required] The ID of the project containing this table. + #[serde(alias="projectId")] + pub project_id: String, + /// [Required] The ID of the table. The ID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum length is 1,024 characters. + #[serde(alias="tableId")] + pub table_id: String, + /// [Required] The ID of the dataset containing this table. + #[serde(alias="datasetId")] + pub dataset_id: String, +} + +impl Part for TableReference {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update tables](struct.TableUpdateCall.html) (request|response) +/// * [insert tables](struct.TableInsertCall.html) (request|response) +/// * [list tables](struct.TableListCall.html) (none) +/// * [delete tables](struct.TableDeleteCall.html) (none) +/// * [get tables](struct.TableGetCall.html) (response) +/// * [patch tables](struct.TablePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Table { + /// [Output-only] The type of the resource. + pub kind: Option, + /// [Optional] The time when this table expires, in milliseconds since the epoch. If not present, the table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. + #[serde(alias="expirationTime")] + pub expiration_time: Option, + /// [Optional] A user-friendly description of this table. + pub description: Option, + /// [Output-only] The time when this table was created, in milliseconds since the epoch. + #[serde(alias="creationTime")] + pub creation_time: Option, + /// [Output-only] An opaque ID uniquely identifying the table. + pub id: Option, + /// [Output-only] The number of rows of data in this table. This property is unavailable for tables that are actively receiving streaming inserts. + #[serde(alias="numRows")] + pub num_rows: Option, + /// [Output-only] The size of the table in bytes. This property is unavailable for tables that are actively receiving streaming inserts. + #[serde(alias="numBytes")] + pub num_bytes: Option, + /// [Output-only] A hash of this resource. + pub etag: Option, + /// [Optional] A descriptive name for this table. + #[serde(alias="friendlyName")] + pub friendly_name: Option, + /// [Output-only] The time when this table was last modified, in milliseconds since the epoch. + #[serde(alias="lastModifiedTime")] + pub last_modified_time: Option, + /// [Optional] Describes the schema of this table. + pub schema: Option, + /// [Output-only] Describes the table type. The following values are supported: TABLE: A normal BigQuery table. VIEW: A virtual table defined by a SQL query. The default value is TABLE. + #[serde(alias="type")] + pub type_: Option, + /// [Required] Reference describing the ID of this table. + #[serde(alias="tableReference")] + pub table_reference: Option, + /// [Output-only] A URL that can be used to access this resource again. + #[serde(alias="selfLink")] + pub self_link: Option, + /// [Optional] The view definition. + pub view: Option, +} + +impl RequestValue for Table {} +impl Resource for Table {} +impl ResponseResult for Table {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert all tabledata](struct.TabledataInsertAllCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableDataInsertAllResponse { + /// The resource type of the response. + pub kind: String, + /// An array of errors for rows that were not inserted. + #[serde(alias="insertErrors")] + pub insert_errors: Vec, +} + +impl ResponseResult for TableDataInsertAllResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query jobs](struct.JobQueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct QueryResponse { + /// The resource type. + pub kind: String, + /// An object with as many results as can be contained within the maximum permitted reply size. To get any additional rows, you can call GetQueryResults and specify the jobReference returned above. + pub rows: Vec, + /// Reference to the Job that was created to run the query. This field will be present even if the original request timed out, in which case GetQueryResults can be used to read the results once the query has completed. Since this API only returns the first page of results, subsequent pages can be fetched via the same mechanism (GetQueryResults). + #[serde(alias="jobReference")] + pub job_reference: JobReference, + /// Whether the query result was fetched from the query cache. + #[serde(alias="cacheHit")] + pub cache_hit: bool, + /// Whether the query has completed or not. If rows or totalRows are present, this will always be true. If this is false, totalRows will not be available. + #[serde(alias="jobComplete")] + pub job_complete: bool, + /// The total number of rows in the complete query result set, which can be more than the number of rows in this single page of results. + #[serde(alias="totalRows")] + pub total_rows: String, + /// The total number of bytes processed for this query. If this query was a dry run, this is the number of bytes that would be processed if the query were run. + #[serde(alias="totalBytesProcessed")] + pub total_bytes_processed: String, + /// A token used for paging results. + #[serde(alias="pageToken")] + pub page_token: String, + /// The schema of the results. Present only when the query completes successfully. + pub schema: TableSchema, +} + +impl ResponseResult for QueryResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobConfigurationTableCopy { + /// [Optional] Specifies whether the job is allowed to create new tables. The following values are supported: CREATE_IF_NEEDED: If the table does not exist, BigQuery creates the table. CREATE_NEVER: The table must already exist. If it does not, a 'notFound' error is returned in the job result. The default value is CREATE_IF_NEEDED. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="createDisposition")] + pub create_disposition: String, + /// [Pick one] Source tables to copy. + #[serde(alias="sourceTables")] + pub source_tables: Vec, + /// [Optional] Specifies the action that occurs if the destination table already exists. The following values are supported: WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data. WRITE_APPEND: If the table already exists, BigQuery appends the data to the table. WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result. The default value is WRITE_EMPTY. Each action is atomic and only occurs if BigQuery is able to complete the job successfully. Creation, truncation and append actions occur as one atomic update upon job completion. + #[serde(alias="writeDisposition")] + pub write_disposition: String, + /// [Required] The destination table + #[serde(alias="destinationTable")] + pub destination_table: TableReference, + /// [Pick one] Source table to copy. + #[serde(alias="sourceTable")] + pub source_table: TableReference, +} + +impl Part for JobConfigurationTableCopy {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *table* resources. +/// It is not used directly, but through the `Bigquery` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.tables(); +/// # } +/// ``` +pub struct TableMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TableMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. + pub fn update(&self, request: &Table, project_id: &str, dataset_id: &str, table_id: &str) -> TableUpdateCall<'a, C, NC, A> { + TableUpdateCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new, empty table in the dataset. + pub fn insert(&self, request: &Table, project_id: &str, dataset_id: &str) -> TableInsertCall<'a, C, NC, A> { + TableInsertCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all tables in the specified dataset. + pub fn list(&self, project_id: &str, dataset_id: &str) -> TableListCall<'a, C, NC, A> { + TableListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted. + pub fn delete(&self, project_id: &str, dataset_id: &str, table_id: &str) -> TableDeleteCall<'a, C, NC, A> { + TableDeleteCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the specified table resource by table ID. This method does not return the data in the table, it only returns the table resource, which describes the structure of this table. + pub fn get(&self, project_id: &str, dataset_id: &str, table_id: &str) -> TableGetCall<'a, C, NC, A> { + TableGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. This method supports patch semantics. + pub fn patch(&self, request: &Table, project_id: &str, dataset_id: &str, table_id: &str) -> TablePatchCall<'a, C, NC, A> { + TablePatchCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *dataset* resources. +/// It is not used directly, but through the `Bigquery` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.datasets(); +/// # } +/// ``` +pub struct DatasetMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DatasetMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. This method supports patch semantics. + pub fn patch(&self, request: &Dataset, project_id: &str, dataset_id: &str) -> DatasetPatchCall<'a, C, NC, A> { + DatasetPatchCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the dataset specified by datasetID. + pub fn get(&self, project_id: &str, dataset_id: &str) -> DatasetGetCall<'a, C, NC, A> { + DatasetGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all the datasets in the specified project to which the caller has read access; however, a project owner can list (but not necessarily get) all datasets in his project. + pub fn list(&self, project_id: &str) -> DatasetListCall<'a, C, NC, A> { + DatasetListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _all: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. + pub fn update(&self, request: &Dataset, project_id: &str, dataset_id: &str) -> DatasetUpdateCall<'a, C, NC, A> { + DatasetUpdateCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the dataset specified by the datasetId value. Before you can delete a dataset, you must delete all its tables, either manually or by specifying deleteContents. Immediately after deletion, you can create another dataset with the same name. + pub fn delete(&self, project_id: &str, dataset_id: &str) -> DatasetDeleteCall<'a, C, NC, A> { + DatasetDeleteCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _delete_contents: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new empty dataset. + pub fn insert(&self, request: &Dataset, project_id: &str) -> DatasetInsertCall<'a, C, NC, A> { + DatasetInsertCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *job* resources. +/// It is not used directly, but through the `Bigquery` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `get_query_results(...)`, `insert(...)`, `list(...)` and `query(...)` +/// // to build up your call. +/// let rb = hub.jobs(); +/// # } +/// ``` +pub struct JobMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for JobMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Runs a BigQuery SQL query synchronously and returns query results if the query completes within a specified timeout. + pub fn query(&self, request: &QueryRequest, project_id: &str) -> JobQueryCall<'a, C, NC, A> { + JobQueryCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the results of a query job. + pub fn get_query_results(&self, project_id: &str, job_id: &str) -> JobGetQueryResultCall<'a, C, NC, A> { + JobGetQueryResultCall { + hub: self.hub, + _project_id: project_id.to_string(), + _job_id: job_id.to_string(), + _timeout_ms: Default::default(), + _start_index: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all the Jobs in the specified project that were started by the user. The job list returns in reverse chronological order of when the jobs were created, starting with the most recent job created. + pub fn list(&self, project_id: &str) -> JobListCall<'a, C, NC, A> { + JobListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _state_filter: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _all_users: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the specified job by ID. + pub fn get(&self, project_id: &str, job_id: &str) -> JobGetCall<'a, C, NC, A> { + JobGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _job_id: job_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Starts a new asynchronous job. + pub fn insert(&self, request: &Job, project_id: &str) -> JobInsertCall<'a, C, NC, A> { + JobInsertCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *tabledata* resources. +/// It is not used directly, but through the `Bigquery` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `insert_all(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.tabledata(); +/// # } +/// ``` +pub struct TabledataMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TabledataMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TabledataMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Streams data into BigQuery one record at a time without needing to run a load job. + pub fn insert_all(&self, request: &TableDataInsertAllRequest, project_id: &str, dataset_id: &str, table_id: &str) -> TabledataInsertAllCall<'a, C, NC, A> { + TabledataInsertAllCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves table data from a specified set of rows. + pub fn list(&self, project_id: &str, dataset_id: &str, table_id: &str) -> TabledataListCall<'a, C, NC, A> { + TabledataListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _dataset_id: dataset_id.to_string(), + _table_id: table_id.to_string(), + _start_index: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *project* resources. +/// It is not used directly, but through the `Bigquery` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-bigquery2" as bigquery2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use bigquery2::Bigquery; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProjectMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists the projects to which you have at least read access. + pub fn list(&self) -> ProjectListCall<'a, C, NC, A> { + ProjectListCall { + hub: self.hub, + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. +/// +/// A builder for the *update* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Table; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Table = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().update(&req, "projectId", "datasetId", "tableId") +/// .doit(); +/// # } +/// ``` +pub struct TableUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Table, + _project_id: String, + _dataset_id: String, + _table_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TableUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Table)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + for &field in ["alt", "projectId", "datasetId", "tableId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Table) -> TableUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the table to update + pub fn project_id(mut self, new_value: &str) -> TableUpdateCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the table to update + pub fn dataset_id(mut self, new_value: &str) -> TableUpdateCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the table to update + pub fn table_id(mut self, new_value: &str) -> TableUpdateCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TableUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TableUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TableUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new, empty table in the dataset. +/// +/// A builder for the *insert* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Table; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Table = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().insert(&req, "projectId", "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct TableInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Table, + _project_id: String, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TableInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Table)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "projectId", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Table) -> TableInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the new table + pub fn project_id(mut self, new_value: &str) -> TableInsertCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the new table + pub fn dataset_id(mut self, new_value: &str) -> TableInsertCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TableInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TableInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TableInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all tables in the specified dataset. +/// +/// A builder for the *list* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().list("projectId", "datasetId") +/// .page_token("gubergren") +/// .max_results(6) +/// .doit(); +/// # } +/// ``` +pub struct TableListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TableListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TableList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "projectId", "datasetId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the tables to list + pub fn project_id(mut self, new_value: &str) -> TableListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the tables to list + pub fn dataset_id(mut self, new_value: &str) -> TableListCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, to request the next page of results + pub fn page_token(mut self, new_value: &str) -> TableListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> TableListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TableListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TableListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TableListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the table specified by tableId from the dataset. If the table contains data, all the data will be deleted. +/// +/// A builder for the *delete* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().delete("projectId", "datasetId", "tableId") +/// .doit(); +/// # } +/// ``` +pub struct TableDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _table_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TableDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + for &field in ["projectId", "datasetId", "tableId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the table to delete + pub fn project_id(mut self, new_value: &str) -> TableDeleteCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the table to delete + pub fn dataset_id(mut self, new_value: &str) -> TableDeleteCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the table to delete + pub fn table_id(mut self, new_value: &str) -> TableDeleteCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TableDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TableDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TableDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the specified table resource by table ID. This method does not return the data in the table, it only returns the table resource, which describes the structure of this table. +/// +/// A builder for the *get* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().get("projectId", "datasetId", "tableId") +/// .doit(); +/// # } +/// ``` +pub struct TableGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _table_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TableGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TableGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Table)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + for &field in ["alt", "projectId", "datasetId", "tableId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the requested table + pub fn project_id(mut self, new_value: &str) -> TableGetCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the requested table + pub fn dataset_id(mut self, new_value: &str) -> TableGetCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the requested table + pub fn table_id(mut self, new_value: &str) -> TableGetCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TableGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TableGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TableGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates information in an existing table. The update method replaces the entire table resource, whereas the patch method only replaces fields that are provided in the submitted table resource. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *table* resource. +/// It is not used directly, but through a `TableMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Table; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Table = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tables().patch(&req, "projectId", "datasetId", "tableId") +/// .doit(); +/// # } +/// ``` +pub struct TablePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Table, + _project_id: String, + _dataset_id: String, + _table_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TablePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TablePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Table)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tables.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + for &field in ["alt", "projectId", "datasetId", "tableId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Table) -> TablePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the table to update + pub fn project_id(mut self, new_value: &str) -> TablePatchCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the table to update + pub fn dataset_id(mut self, new_value: &str) -> TablePatchCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the table to update + pub fn table_id(mut self, new_value: &str) -> TablePatchCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TablePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TablePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TablePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Dataset; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Dataset = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().patch(&req, "projectId", "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Dataset, + _project_id: String, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "projectId", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Dataset) -> DatasetPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the dataset being updated + pub fn project_id(mut self, new_value: &str) -> DatasetPatchCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the dataset being updated + pub fn dataset_id(mut self, new_value: &str) -> DatasetPatchCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the dataset specified by datasetID. +/// +/// A builder for the *get* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().get("projectId", "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "projectId", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the requested dataset + pub fn project_id(mut self, new_value: &str) -> DatasetGetCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the requested dataset + pub fn dataset_id(mut self, new_value: &str) -> DatasetGetCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all the datasets in the specified project to which the caller has read access; however, a project owner can list (but not necessarily get) all datasets in his project. +/// +/// A builder for the *list* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().list("projectId") +/// .page_token("Lorem") +/// .max_results(26) +/// .all(false) +/// .doit(); +/// # } +/// ``` +pub struct DatasetListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _page_token: Option, + _max_results: Option, + _all: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatasetList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._all { + params.push(("all", value.to_string())); + } + for &field in ["alt", "projectId", "pageToken", "maxResults", "all"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the datasets to be listed + pub fn project_id(mut self, new_value: &str) -> DatasetListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, to request the next page of results + pub fn page_token(mut self, new_value: &str) -> DatasetListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> DatasetListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *all* query property to the given value. + /// + /// + /// Whether to list all datasets, including hidden ones + pub fn all(mut self, new_value: bool) -> DatasetListCall<'a, C, NC, A> { + self._all = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates information in an existing dataset. The update method replaces the entire dataset resource, whereas the patch method only replaces fields that are provided in the submitted dataset resource. +/// +/// A builder for the *update* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Dataset; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Dataset = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().update(&req, "projectId", "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Dataset, + _project_id: String, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "projectId", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Dataset) -> DatasetUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the dataset being updated + pub fn project_id(mut self, new_value: &str) -> DatasetUpdateCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the dataset being updated + pub fn dataset_id(mut self, new_value: &str) -> DatasetUpdateCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the dataset specified by the datasetId value. Before you can delete a dataset, you must delete all its tables, either manually or by specifying deleteContents. Immediately after deletion, you can create another dataset with the same name. +/// +/// A builder for the *delete* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().delete("projectId", "datasetId") +/// .delete_contents(false) +/// .doit(); +/// # } +/// ``` +pub struct DatasetDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _delete_contents: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._delete_contents { + params.push(("deleteContents", value.to_string())); + } + for &field in ["projectId", "datasetId", "deleteContents"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the dataset being deleted + pub fn project_id(mut self, new_value: &str) -> DatasetDeleteCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of dataset being deleted + pub fn dataset_id(mut self, new_value: &str) -> DatasetDeleteCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delete contents* query property to the given value. + /// + /// + /// If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False + pub fn delete_contents(mut self, new_value: bool) -> DatasetDeleteCall<'a, C, NC, A> { + self._delete_contents = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new empty dataset. +/// +/// A builder for the *insert* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Dataset; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Dataset = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().insert(&req, "projectId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Dataset, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.datasets.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Dataset) -> DatasetInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the new dataset + pub fn project_id(mut self, new_value: &str) -> DatasetInsertCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Runs a BigQuery SQL query synchronously and returns query results if the query completes within a specified timeout. +/// +/// A builder for the *query* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::QueryRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: QueryRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().query(&req, "projectId") +/// .doit(); +/// # } +/// ``` +pub struct JobQueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: QueryRequest, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobQueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobQueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, QueryResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.jobs.query", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/queries".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &QueryRequest) -> JobQueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the project billed for the query + pub fn project_id(mut self, new_value: &str) -> JobQueryCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobQueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobQueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobQueryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the results of a query job. +/// +/// A builder for the *getQueryResults* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().get_query_results("projectId", "jobId") +/// .timeout_ms(64) +/// .start_index("aliquyam") +/// .page_token("accusam") +/// .max_results(45) +/// .doit(); +/// # } +/// ``` +pub struct JobGetQueryResultCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _job_id: String, + _timeout_ms: Option, + _start_index: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobGetQueryResultCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobGetQueryResultCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetQueryResultsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.jobs.getQueryResults", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._timeout_ms { + params.push(("timeoutMs", value.to_string())); + } + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "projectId", "jobId", "timeoutMs", "startIndex", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/queries/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the query job + pub fn project_id(mut self, new_value: &str) -> JobGetQueryResultCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job ID of the query job + pub fn job_id(mut self, new_value: &str) -> JobGetQueryResultCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *timeout ms* query property to the given value. + /// + /// + /// How long to wait for the query to complete, in milliseconds, before returning. Default is to return immediately. If the timeout passes before the job completes, the request will fail with a TIMEOUT error + pub fn timeout_ms(mut self, new_value: u32) -> JobGetQueryResultCall<'a, C, NC, A> { + self._timeout_ms = Some(new_value); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Zero-based index of the starting row + pub fn start_index(mut self, new_value: &str) -> JobGetQueryResultCall<'a, C, NC, A> { + self._start_index = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, to request the next page of results + pub fn page_token(mut self, new_value: &str) -> JobGetQueryResultCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to read + pub fn max_results(mut self, new_value: u32) -> JobGetQueryResultCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobGetQueryResultCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobGetQueryResultCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobGetQueryResultCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all the Jobs in the specified project that were started by the user. The job list returns in reverse chronological order of when the jobs were created, starting with the most recent job created. +/// +/// A builder for the *list* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().list("projectId") +/// .add_state_filter("et") +/// .projection("duo") +/// .page_token("et") +/// .max_results(61) +/// .all_users(false) +/// .doit(); +/// # } +/// ``` +pub struct JobListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _state_filter: Vec, + _projection: Option, + _page_token: Option, + _max_results: Option, + _all_users: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, JobList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.jobs.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + if self._state_filter.len() > 0 { + let mut s = String::new(); + for f in self._state_filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("stateFilter", s)); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._all_users { + params.push(("allUsers", value.to_string())); + } + for &field in ["alt", "projectId", "stateFilter", "projection", "pageToken", "maxResults", "allUsers"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/jobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the jobs to list + pub fn project_id(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Append the given value to the *state filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Filter for job state + pub fn add_state_filter(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._state_filter.push(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields + pub fn projection(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, to request the next page of results + pub fn page_token(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> JobListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *all users* query property to the given value. + /// + /// + /// Whether to display jobs owned by all users in the project. Default false + pub fn all_users(mut self, new_value: bool) -> JobListCall<'a, C, NC, A> { + self._all_users = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the specified job by ID. +/// +/// A builder for the *get* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().get("projectId", "jobId") +/// .doit(); +/// # } +/// ``` +pub struct JobGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _job_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Job)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.jobs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + for &field in ["alt", "projectId", "jobId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the requested job + pub fn project_id(mut self, new_value: &str) -> JobGetCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job ID of the requested job + pub fn job_id(mut self, new_value: &str) -> JobGetCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Starts a new asynchronous job. +/// +/// A builder for the *insert* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::Job; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Job = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().insert(&req, "projectId") +/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct JobInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: Job, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, Job)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.jobs.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/bigquery/v2/projects/{projectId}/jobs".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/bigquery/v2/projects/{projectId}/jobs".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut mp_reader: MultiPartReader = Default::default(); + let (mut body_reader, content_type) = match protocol { + "simple" => { + mp_reader.reserve_exact(2); + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone()) + .add_part(&mut reader, size, reader_mime_type.clone()); + let mime_type = mp_reader.mime_type(); + (&mut mp_reader as &mut io::Read, ContentType(mime_type)) + }, + _ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())), + }; + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(content_type) + .body(&mut body_reader); + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 0kb + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Job)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 0kb + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, Job)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Job) -> JobInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the project that will be billed for the job + pub fn project_id(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Streams data into BigQuery one record at a time without needing to run a load job. +/// +/// A builder for the *insertAll* method supported by a *tabledata* resource. +/// It is not used directly, but through a `TabledataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// use bigquery2::TableDataInsertAllRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TableDataInsertAllRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tabledata().insert_all(&req, "projectId", "datasetId", "tableId") +/// .doit(); +/// # } +/// ``` +pub struct TabledataInsertAllCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _request: TableDataInsertAllRequest, + _project_id: String, + _dataset_id: String, + _table_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TabledataInsertAllCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TabledataInsertAllCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TableDataInsertAllResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tabledata.insertAll", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + for &field in ["alt", "projectId", "datasetId", "tableId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}/insertAll".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TableDataInsertAllRequest) -> TabledataInsertAllCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the destination table. + pub fn project_id(mut self, new_value: &str) -> TabledataInsertAllCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the destination table. + pub fn dataset_id(mut self, new_value: &str) -> TabledataInsertAllCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the destination table. + pub fn table_id(mut self, new_value: &str) -> TabledataInsertAllCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TabledataInsertAllCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TabledataInsertAllCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TabledataInsertAllCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves table data from a specified set of rows. +/// +/// A builder for the *list* method supported by a *tabledata* resource. +/// It is not used directly, but through a `TabledataMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.tabledata().list("projectId", "datasetId", "tableId") +/// .start_index("dolor") +/// .page_token("et") +/// .max_results(5) +/// .doit(); +/// # } +/// ``` +pub struct TabledataListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _project_id: String, + _dataset_id: String, + _table_id: String, + _start_index: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TabledataListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TabledataListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TableDataList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.tabledata.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + params.push(("tableId", self._table_id.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "projectId", "datasetId", "tableId", "startIndex", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{datasetId}", "datasetId"), ("{tableId}", "tableId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "datasetId", "tableId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID of the table to read + pub fn project_id(mut self, new_value: &str) -> TabledataListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset ID of the table to read + pub fn dataset_id(mut self, new_value: &str) -> TabledataListCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *table id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Table ID of the table to read + pub fn table_id(mut self, new_value: &str) -> TabledataListCall<'a, C, NC, A> { + self._table_id = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Zero-based index of the starting row to read + pub fn start_index(mut self, new_value: &str) -> TabledataListCall<'a, C, NC, A> { + self._start_index = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, identifying the result set + pub fn page_token(mut self, new_value: &str) -> TabledataListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> TabledataListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TabledataListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TabledataListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TabledataListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the projects to which you have at least read access. +/// +/// A builder for the *list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-bigquery2" as bigquery2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use bigquery2::Bigquery; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Bigquery::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().list() +/// .page_token("amet.") +/// .max_results(74) +/// .doit(); +/// # } +/// ``` +pub struct ProjectListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Bigquery, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProjectList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "bigquery.projects.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/bigquery/v2/projects".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token, returned by a previous call, to request the next page of results + pub fn page_token(mut self, new_value: &str) -> ProjectListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> ProjectListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/blogger3/Cargo.toml b/gen/blogger3/Cargo.toml new file mode 100644 index 0000000000..712fa9ba3f --- /dev/null +++ b/gen/blogger3/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-blogger3" +version = "0.1.0+20150208" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with blogger (protocol v3)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/blogger3" +homepage = "https://developers.google.com/blogger/docs/3.0/getting_started" +documentation = "http://byron.github.io/google-apis-rs/google-blogger3" +license = "MIT" +keywords = ["blogger", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/blogger3/LICENSE.md b/gen/blogger3/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/blogger3/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/blogger3/README.md b/gen/blogger3/README.md new file mode 100644 index 0000000000..f67e59f32d --- /dev/null +++ b/gen/blogger3/README.md @@ -0,0 +1,196 @@ + +The `google-blogger3` library allows access to all features of the *Google blogger* service. + +This documentation was generated from *blogger* crate version *0.1.0+20150208*, where *20150208* is the exact revision of the *blogger:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *blogger* *v3* API can be found at the +[official documentation site](https://developers.google.com/blogger/docs/3.0/getting_started). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-blogger3/struct.Blogger.html) ... + +* [blog user infos](http://byron.github.io/google-apis-rs/google-blogger3/struct.BlogUserInfo.html) + * [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.BlogUserInfoGetCall.html) +* [blogs](http://byron.github.io/google-apis-rs/google-blogger3/struct.Blog.html) + * [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.BlogGetCall.html), [*get by url*](http://byron.github.io/google-apis-rs/google-blogger3/struct.BlogGetByUrlCall.html) and [*list by user*](http://byron.github.io/google-apis-rs/google-blogger3/struct.BlogListByUserCall.html) +* [comments](http://byron.github.io/google-apis-rs/google-blogger3/struct.Comment.html) + * [*approve*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentApproveCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentListCall.html), [*list by blog*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentListByBlogCall.html), [*mark as spam*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentMarkAsSpamCall.html) and [*remove content*](http://byron.github.io/google-apis-rs/google-blogger3/struct.CommentRemoveContentCall.html) +* page views + * [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageViewGetCall.html) +* [pages](http://byron.github.io/google-apis-rs/google-blogger3/struct.Page.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PagePatchCall.html), [*publish*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PagePublishCall.html), [*revert*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageRevertCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PageUpdateCall.html) +* [post user infos](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostUserInfo.html) + * [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostUserInfoGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostUserInfoListCall.html) +* [posts](http://byron.github.io/google-apis-rs/google-blogger3/struct.Post.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostGetCall.html), [*get by path*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostGetByPathCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostPatchCall.html), [*publish*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostPublishCall.html), [*revert*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostRevertCall.html), [*search*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostSearchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-blogger3/struct.PostUpdateCall.html) +* [users](http://byron.github.io/google-apis-rs/google-blogger3/struct.User.html) + * [*get*](http://byron.github.io/google-apis-rs/google-blogger3/struct.UserGetCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-blogger3/struct.Blogger.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-blogger3/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-blogger3/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-blogger3/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.posts().insert(...).doit() +let r = hub.posts().publish(...).doit() +let r = hub.posts().delete(...).doit() +let r = hub.posts().revert(...).doit() +let r = hub.posts().update(...).doit() +let r = hub.posts().get_by_path(...).doit() +let r = hub.posts().search(...).doit() +let r = hub.posts().patch(...).doit() +let r = hub.posts().list(...).doit() +let r = hub.posts().get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-blogger3 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-blogger3" as blogger3; +use blogger3::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use blogger3::Blogger; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Blogger::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.posts().list("blogId") + .view("sit") + .add_status("Stet") + .start_date("sed") + .page_token("et") + .order_by("dolores") + .max_results(38) + .labels("accusam") + .fetch_images(true) + .fetch_bodies(false) + .end_date("amet.") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-blogger3/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-blogger3/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-blogger3/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-blogger3/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-blogger3/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-blogger3/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-blogger3/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-blogger3/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-blogger3/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-blogger3/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-blogger3/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-blogger3/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-blogger3/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **blogger3** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/blogger3/src/cmn.rs b/gen/blogger3/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/blogger3/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/blogger3/src/lib.rs b/gen/blogger3/src/lib.rs new file mode 100644 index 0000000000..a1a69925e6 --- /dev/null +++ b/gen/blogger3/src/lib.rs @@ -0,0 +1,11200 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *blogger* crate version *0.1.0+20150208*, where *20150208* is the exact revision of the *blogger:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *blogger* *v3* API can be found at the +//! [official documentation site](https://developers.google.com/blogger/docs/3.0/getting_started). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/blogger3). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Blogger.html) ... +//! +//! * [blog user infos](struct.BlogUserInfo.html) +//! * [*get*](struct.BlogUserInfoGetCall.html) +//! * [blogs](struct.Blog.html) +//! * [*get*](struct.BlogGetCall.html), [*get by url*](struct.BlogGetByUrlCall.html) and [*list by user*](struct.BlogListByUserCall.html) +//! * [comments](struct.Comment.html) +//! * [*approve*](struct.CommentApproveCall.html), [*delete*](struct.CommentDeleteCall.html), [*get*](struct.CommentGetCall.html), [*list*](struct.CommentListCall.html), [*list by blog*](struct.CommentListByBlogCall.html), [*mark as spam*](struct.CommentMarkAsSpamCall.html) and [*remove content*](struct.CommentRemoveContentCall.html) +//! * page views +//! * [*get*](struct.PageViewGetCall.html) +//! * [pages](struct.Page.html) +//! * [*delete*](struct.PageDeleteCall.html), [*get*](struct.PageGetCall.html), [*insert*](struct.PageInsertCall.html), [*list*](struct.PageListCall.html), [*patch*](struct.PagePatchCall.html), [*publish*](struct.PagePublishCall.html), [*revert*](struct.PageRevertCall.html) and [*update*](struct.PageUpdateCall.html) +//! * [post user infos](struct.PostUserInfo.html) +//! * [*get*](struct.PostUserInfoGetCall.html) and [*list*](struct.PostUserInfoListCall.html) +//! * [posts](struct.Post.html) +//! * [*delete*](struct.PostDeleteCall.html), [*get*](struct.PostGetCall.html), [*get by path*](struct.PostGetByPathCall.html), [*insert*](struct.PostInsertCall.html), [*list*](struct.PostListCall.html), [*patch*](struct.PostPatchCall.html), [*publish*](struct.PostPublishCall.html), [*revert*](struct.PostRevertCall.html), [*search*](struct.PostSearchCall.html) and [*update*](struct.PostUpdateCall.html) +//! * [users](struct.User.html) +//! * [*get*](struct.UserGetCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Blogger.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.posts().insert(...).doit() +//! let r = hub.posts().publish(...).doit() +//! let r = hub.posts().delete(...).doit() +//! let r = hub.posts().revert(...).doit() +//! let r = hub.posts().update(...).doit() +//! let r = hub.posts().get_by_path(...).doit() +//! let r = hub.posts().search(...).doit() +//! let r = hub.posts().patch(...).doit() +//! let r = hub.posts().list(...).doit() +//! let r = hub.posts().get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-blogger3 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-blogger3" as blogger3; +//! use blogger3::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use blogger3::Blogger; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Blogger::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.posts().list("blogId") +//! .view("labore") +//! .add_status("sea") +//! .start_date("nonumy") +//! .page_token("dolores") +//! .order_by("gubergren") +//! .max_results(6) +//! .labels("aliquyam") +//! .fetch_images(false) +//! .fetch_bodies(false) +//! .end_date("justo") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your Blogger account + Full, + + /// View your Blogger account + Readonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/blogger", + Scope::Readonly => "https://www.googleapis.com/auth/blogger.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Blogger related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// use blogger3::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().list("blogId") +/// .view("et") +/// .add_status("et") +/// .start_date("diam") +/// .page_token("ipsum") +/// .order_by("Lorem") +/// .max_results(80) +/// .labels("duo") +/// .fetch_images(true) +/// .fetch_bodies(true) +/// .end_date("Lorem") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Blogger { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Blogger {} + +impl<'a, C, NC, A> Blogger + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Blogger { + Blogger { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn blog_user_infos(&'a self) -> BlogUserInfoMethods<'a, C, NC, A> { + BlogUserInfoMethods { hub: &self } + } + pub fn blogs(&'a self) -> BlogMethods<'a, C, NC, A> { + BlogMethods { hub: &self } + } + pub fn comments(&'a self) -> CommentMethods<'a, C, NC, A> { + CommentMethods { hub: &self } + } + pub fn page_views(&'a self) -> PageViewMethods<'a, C, NC, A> { + PageViewMethods { hub: &self } + } + pub fn pages(&'a self) -> PageMethods<'a, C, NC, A> { + PageMethods { hub: &self } + } + pub fn post_user_infos(&'a self) -> PostUserInfoMethods<'a, C, NC, A> { + PostUserInfoMethods { hub: &self } + } + pub fn posts(&'a self) -> PostMethods<'a, C, NC, A> { + PostMethods { hub: &self } + } + pub fn users(&'a self) -> UserMethods<'a, C, NC, A> { + UserMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Data about the blog containing this Post. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostBlog { + /// The identifier of the Blog that contains this Post. + pub id: String, +} + +impl NestedType for PostBlog {} +impl Part for PostBlog {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogPerUserInfo { + /// True if the user has Admin level access to the blog. + #[serde(alias="hasAdminAccess")] + pub has_admin_access: bool, + /// The kind of this entity. Always blogger#blogPerUserInfo + pub kind: String, + /// Access permissions that the user has for the blog (ADMIN, AUTHOR, or READER). + pub role: String, + /// The Photo Album Key for the user when adding photos to the blog + #[serde(alias="photosAlbumKey")] + pub photos_album_key: String, + /// ID of the User + #[serde(alias="userId")] + pub user_id: String, + /// ID of the Blog resource + #[serde(alias="blogId")] + pub blog_id: String, +} + +impl Part for BlogPerUserInfo {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PostPerUserInfo { + /// The kind of this entity. Always blogger#postPerUserInfo + pub kind: String, + /// ID of the Post resource. + #[serde(alias="postId")] + pub post_id: String, + /// ID of the User. + #[serde(alias="userId")] + pub user_id: String, + /// ID of the Blog that the post resource belongs to. + #[serde(alias="blogId")] + pub blog_id: String, + /// True if the user has Author level access to the post. + #[serde(alias="hasEditAccess")] + pub has_edit_access: bool, +} + +impl Part for PostPerUserInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list by user blogs](struct.BlogListByUserCall.html) (none) +/// * [get blogs](struct.BlogGetCall.html) (response) +/// * [get by url blogs](struct.BlogGetByUrlCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Blog { + /// The status of the blog. + pub status: String, + /// The kind of this entry. Always blogger#blog + pub kind: String, + /// The description of this blog. This is displayed underneath the title. + pub description: String, + /// The locale this Blog is set to. + pub locale: BlogLocale, + /// The JSON custom meta-data for the Blog + #[serde(alias="customMetaData")] + pub custom_meta_data: String, + /// The container of posts in this blog. + pub posts: BlogPosts, + /// RFC 3339 date-time when this blog was last updated. + pub updated: String, + /// The identifier for this resource. + pub id: String, + /// The URL where this blog is published. + pub url: String, + /// RFC 3339 date-time when this blog was published. + pub published: String, + /// The container of pages in this blog. + pub pages: BlogPages, + /// The API REST URL to fetch this resource from. + #[serde(alias="selfLink")] + pub self_link: String, + /// The name of this blog. This is displayed as the title. + pub name: String, +} + +impl Resource for Blog {} +impl ResponseResult for Blog {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list post user infos](struct.PostUserInfoListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PostUserInfosList { + /// Pagination token to fetch the next page, if one exists. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The list of Posts with User information for the post, for this Blog. + pub items: Vec, + /// The kind of this entity. Always blogger#postList + pub kind: String, +} + +impl ResponseResult for PostUserInfosList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get blog user infos](struct.BlogUserInfoGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogUserInfo { + /// The Blog resource. + pub blog: Blog, + /// The kind of this entity. Always blogger#blogUserInfo + pub kind: String, + /// Information about a User for the Blog. + pub blog_user_info: BlogPerUserInfo, +} + +impl Resource for BlogUserInfo {} +impl ResponseResult for BlogUserInfo {} + + +/// Data about the comment this is in reply to. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentInReplyTo { + /// The identified of the parent of this comment. + pub id: String, +} + +impl NestedType for CommentInReplyTo {} +impl Part for CommentInReplyTo {} + + +/// The author of this Comment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentAuthor { + /// The URL of the Comment creator's Profile page. + pub url: String, + /// The comment creator's avatar. + pub image: CommentAuthorImage, + /// The display name. + #[serde(alias="displayName")] + pub display_name: String, + /// The identifier of the Comment creator. + pub id: String, +} + +impl NestedType for CommentAuthor {} +impl Part for CommentAuthor {} + + +/// The page author's avatar. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PageAuthorImage { + /// The page author's avatar URL. + pub url: String, +} + +impl NestedType for PageAuthorImage {} +impl Part for PageAuthorImage {} + + +/// Data about the post containing this comment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentPost { + /// The identifier of the post containing this comment. + pub id: String, +} + +impl NestedType for CommentPost {} +impl Part for CommentPost {} + + +/// The container of blogs for this user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserBlogs { + /// The URL of the Blogs for this user. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl NestedType for UserBlogs {} +impl Part for UserBlogs {} + + +/// The container of comments on this Post. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostReplies { + /// The count of comments on this post. + #[serde(alias="totalItems")] + pub total_items: String, + /// The List of Comments for this Post. + pub items: Vec, + /// The URL of the comments on this post. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl NestedType for PostReplies {} +impl Part for PostReplies {} + + +/// The container of posts in this blog. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PageviewsCounts { + /// Count of page views for the given time range + pub count: String, + /// Time range the given count applies to + #[serde(alias="timeRange")] + pub time_range: String, +} + +impl NestedType for PageviewsCounts {} +impl Part for PageviewsCounts {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list by user blogs](struct.BlogListByUserCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogList { + /// The list of Blogs this user has Authorship or Admin rights over. + pub items: Vec, + /// The kind of this entity. Always blogger#blogList + pub kind: String, + /// Admin level list of blog per-user information + #[serde(alias="blogUserInfos")] + pub blog_user_infos: Vec, +} + +impl ResponseResult for BlogList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get users](struct.UserGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct User { + /// Profile summary information. + pub about: String, + /// The display name. + #[serde(alias="displayName")] + pub display_name: String, + /// The timestamp of when this profile was created, in seconds since epoch. + pub created: String, + /// This user's locale + pub locale: UserLocale, + /// The container of blogs for this user. + pub blogs: UserBlogs, + /// The kind of this entity. Always blogger#user + pub kind: String, + /// The user's profile page. + pub url: String, + /// The identifier for this User. + pub id: String, + /// The API REST URL to fetch this resource from. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl Resource for User {} +impl ResponseResult for User {} + + +/// The Post author's avatar. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostAuthorImage { + /// The Post author's avatar URL. + pub url: String, +} + +impl NestedType for PostAuthorImage {} +impl Part for PostAuthorImage {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert posts](struct.PostInsertCall.html) (request|response) +/// * [publish posts](struct.PostPublishCall.html) (response) +/// * [delete posts](struct.PostDeleteCall.html) (none) +/// * [revert posts](struct.PostRevertCall.html) (response) +/// * [update posts](struct.PostUpdateCall.html) (request|response) +/// * [get by path posts](struct.PostGetByPathCall.html) (response) +/// * [search posts](struct.PostSearchCall.html) (none) +/// * [patch posts](struct.PostPatchCall.html) (request|response) +/// * [list posts](struct.PostListCall.html) (none) +/// * [get posts](struct.PostGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Post { + /// Status of the post. Only set for admin-level requests + pub status: Option, + /// RFC 3339 date-time when this Post was last updated. + pub updated: Option, + /// Comment control and display setting for readers of this post. + #[serde(alias="readerComments")] + pub reader_comments: Option, + /// The list of labels this Post was tagged with. + pub labels: Option>, + /// The container of comments on this Post. + pub replies: Option, + /// Display image for the Post. + pub images: Option>, + /// The identifier of this Post. + pub id: Option, + /// Data about the blog containing this Post. + pub blog: Option, + /// The kind of this entity. Always blogger#post + pub kind: Option, + /// The title link URL, similar to atom's related link. + #[serde(alias="titleLink")] + pub title_link: Option, + /// The author of this Post. + pub author: Option, + /// The URL where this Post is displayed. + pub url: Option, + /// The title of the Post. + pub title: Option, + /// The JSON meta-data for the Post. + #[serde(alias="customMetaData")] + pub custom_meta_data: Option, + /// The content of the Post. May contain HTML markup. + pub content: Option, + /// Etag of the resource. + pub etag: Option, + /// The location for geotagged posts. + pub location: Option, + /// RFC 3339 date-time when this Post was published. + pub published: Option, + /// The API REST URL to fetch this resource from. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Post {} +impl Resource for Post {} +impl ResponseResult for Post {} + + +/// The location for geotagged posts. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostLocation { + /// Location's latitude. + pub lat: f64, + /// Location's longitude. + pub lng: f64, + /// Location's viewport span. Can be used when rendering a map preview. + pub span: String, + /// Location name. + pub name: String, +} + +impl NestedType for PostLocation {} +impl Part for PostLocation {} + + +/// The author of this Post. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostAuthor { + /// The URL of the Post creator's Profile page. + pub url: String, + /// The Post author's avatar. + pub image: PostAuthorImage, + /// The display name. + #[serde(alias="displayName")] + pub display_name: String, + /// The identifier of the Post creator. + pub id: String, +} + +impl NestedType for PostAuthor {} +impl Part for PostAuthor {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list by blog comments](struct.CommentListByBlogCall.html) (response) +/// * [list comments](struct.CommentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CommentList { + /// Pagination token to fetch the next page, if one exists. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The List of Comments for a Post. + pub items: Vec, + /// The kind of this entry. Always blogger#commentList + pub kind: String, + /// Pagination token to fetch the previous page, if one exists. + #[serde(alias="prevPageToken")] + pub prev_page_token: String, +} + +impl ResponseResult for CommentList {} + + +/// Display image for the Post. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostImages { + /// no description provided + pub url: String, +} + +impl NestedType for PostImages {} +impl Part for PostImages {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list posts](struct.PostListCall.html) (response) +/// * [search posts](struct.PostSearchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PostList { + /// Pagination token to fetch the next page, if one exists. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The list of Posts for this Blog. + pub items: Vec, + /// The kind of this entity. Always blogger#postList + pub kind: String, +} + +impl ResponseResult for PostList {} + + +/// The comment creator's avatar. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentAuthorImage { + /// The comment creator's avatar URL. + pub url: String, +} + +impl NestedType for CommentAuthorImage {} +impl Part for CommentAuthorImage {} + + +/// The container of pages in this blog. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogPages { + /// The count of pages in this blog. + #[serde(alias="totalItems")] + pub total_items: i32, + /// The URL of the container for pages in this blog. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl NestedType for BlogPages {} +impl Part for BlogPages {} + + +/// The container of posts in this blog. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogPosts { + /// The count of posts in this blog. + #[serde(alias="totalItems")] + pub total_items: i32, + /// The List of Posts for this Blog. + pub items: Vec, + /// The URL of the container for posts in this blog. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl NestedType for BlogPosts {} +impl Part for BlogPosts {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update pages](struct.PageUpdateCall.html) (request|response) +/// * [get pages](struct.PageGetCall.html) (response) +/// * [insert pages](struct.PageInsertCall.html) (request|response) +/// * [publish pages](struct.PagePublishCall.html) (response) +/// * [list pages](struct.PageListCall.html) (none) +/// * [patch pages](struct.PagePatchCall.html) (request|response) +/// * [revert pages](struct.PageRevertCall.html) (response) +/// * [delete pages](struct.PageDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Page { + /// The status of the page for admin resources (either LIVE or DRAFT). + pub status: Option, + /// Data about the blog containing this Page. + pub blog: Option, + /// The kind of this entity. Always blogger#page + pub kind: Option, + /// The title of this entity. This is the name displayed in the Admin user interface. + pub title: Option, + /// The URL that this Page is displayed at. + pub url: Option, + /// The author of this Page. + pub author: Option, + /// RFC 3339 date-time when this Page was last updated. + pub updated: Option, + /// The body content of this Page, in HTML. + pub content: Option, + /// Etag of the resource. + pub etag: Option, + /// RFC 3339 date-time when this Page was published. + pub published: Option, + /// The identifier for this resource. + pub id: Option, + /// The API REST URL to fetch this resource from. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Page {} +impl Resource for Page {} +impl ResponseResult for Page {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list by blog comments](struct.CommentListByBlogCall.html) (none) +/// * [get comments](struct.CommentGetCall.html) (response) +/// * [mark as spam comments](struct.CommentMarkAsSpamCall.html) (response) +/// * [list comments](struct.CommentListCall.html) (none) +/// * [remove content comments](struct.CommentRemoveContentCall.html) (response) +/// * [approve comments](struct.CommentApproveCall.html) (response) +/// * [delete comments](struct.CommentDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Comment { + /// The status of the comment (only populated for admin users) + pub status: String, + /// Data about the comment this is in reply to. + #[serde(alias="inReplyTo")] + pub in_reply_to: CommentInReplyTo, + /// The kind of this entry. Always blogger#comment + pub kind: String, + /// The author of this Comment. + pub author: CommentAuthor, + /// RFC 3339 date-time when this comment was last updated. + pub updated: String, + /// Data about the blog containing this comment. + pub blog: CommentBlog, + /// RFC 3339 date-time when this comment was published. + pub published: String, + /// Data about the post containing this comment. + pub post: CommentPost, + /// The actual content of the comment. May include HTML markup. + pub content: String, + /// The identifier for this resource. + pub id: String, + /// The API REST URL to fetch this resource from. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl Resource for Comment {} +impl ResponseResult for Comment {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list post user infos](struct.PostUserInfoListCall.html) (none) +/// * [get post user infos](struct.PostUserInfoGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PostUserInfo { + /// The kind of this entity. Always blogger#postUserInfo + pub kind: String, + /// The Post resource. + pub post: Post, + /// Information about a User for the Post. + pub post_user_info: PostPerUserInfo, +} + +impl Resource for PostUserInfo {} +impl ResponseResult for PostUserInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get page views](struct.PageViewGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Pageviews { + /// The container of posts in this blog. + pub counts: Vec, + /// Blog Id + #[serde(alias="blogId")] + pub blog_id: String, + /// The kind of this entry. Always blogger#page_views + pub kind: String, +} + +impl ResponseResult for Pageviews {} + + +/// The author of this Page. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PageAuthor { + /// The URL of the Page creator's Profile page. + pub url: String, + /// The page author's avatar. + pub image: PageAuthorImage, + /// The display name. + #[serde(alias="displayName")] + pub display_name: String, + /// The identifier of the Page creator. + pub id: String, +} + +impl NestedType for PageAuthor {} +impl Part for PageAuthor {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list pages](struct.PageListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PageList { + /// Pagination token to fetch the next page, if one exists. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The list of Pages for a Blog. + pub items: Vec, + /// The kind of this entity. Always blogger#pageList + pub kind: String, +} + +impl ResponseResult for PageList {} + + +/// This user's locale +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserLocale { + /// The user's country setting. + pub country: String, + /// The user's language variant setting. + pub variant: String, + /// The user's language setting. + pub language: String, +} + +impl NestedType for UserLocale {} +impl Part for UserLocale {} + + +/// Data about the blog containing this comment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentBlog { + /// The identifier of the blog containing this comment. + pub id: String, +} + +impl NestedType for CommentBlog {} +impl Part for CommentBlog {} + + +/// Data about the blog containing this Page. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PageBlog { + /// The identifier of the blog containing this page. + pub id: String, +} + +impl NestedType for PageBlog {} +impl Part for PageBlog {} + + +/// The locale this Blog is set to. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BlogLocale { + /// The country this blog's locale is set to. + pub country: String, + /// The language variant this blog is authored in. + pub variant: String, + /// The language this blog is authored in. + pub language: String, +} + +impl NestedType for BlogLocale {} +impl Part for BlogLocale {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *pageView* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.page_views(); +/// # } +/// ``` +pub struct PageViewMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PageViewMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageViewMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve pageview stats for a Blog. + pub fn get(&self, blog_id: &str) -> PageViewGetCall<'a, C, NC, A> { + PageViewGetCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _range: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *user* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.users(); +/// # } +/// ``` +pub struct UserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one user by ID. + pub fn get(&self, user_id: &str) -> UserGetCall<'a, C, NC, A> { + UserGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *blog* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `get_by_url(...)` and `list_by_user(...)` +/// // to build up your call. +/// let rb = hub.blogs(); +/// # } +/// ``` +pub struct BlogMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BlogMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of blogs, possibly filtered. + pub fn list_by_user(&self, user_id: &str) -> BlogListByUserCall<'a, C, NC, A> { + BlogListByUserCall { + hub: self.hub, + _user_id: user_id.to_string(), + _view: Default::default(), + _status: Default::default(), + _role: Default::default(), + _fetch_user_info: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one blog by ID. + pub fn get(&self, blog_id: &str) -> BlogGetCall<'a, C, NC, A> { + BlogGetCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _view: Default::default(), + _max_posts: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve a Blog by URL. + pub fn get_by_url(&self, url: &str) -> BlogGetByUrlCall<'a, C, NC, A> { + BlogGetByUrlCall { + hub: self.hub, + _url: url.to_string(), + _view: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *post* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `get_by_path(...)`, `insert(...)`, `list(...)`, `patch(...)`, `publish(...)`, `revert(...)`, `search(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.posts(); +/// # } +/// ``` +pub struct PostMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PostMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Update a post. + pub fn update(&self, request: &Post, blog_id: &str, post_id: &str) -> PostUpdateCall<'a, C, NC, A> { + PostUpdateCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _revert: Default::default(), + _publish: Default::default(), + _max_comments: Default::default(), + _fetch_images: Default::default(), + _fetch_body: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve a Post by Path. + pub fn get_by_path(&self, blog_id: &str, path: &str) -> PostGetByPathCall<'a, C, NC, A> { + PostGetByPathCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _path: path.to_string(), + _view: Default::default(), + _max_comments: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get a post by ID. + pub fn get(&self, blog_id: &str, post_id: &str) -> PostGetCall<'a, C, NC, A> { + PostGetCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _view: Default::default(), + _max_comments: Default::default(), + _fetch_images: Default::default(), + _fetch_body: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a post. + pub fn insert(&self, request: &Post, blog_id: &str) -> PostInsertCall<'a, C, NC, A> { + PostInsertCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _is_draft: Default::default(), + _fetch_images: Default::default(), + _fetch_body: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Publishes a draft post, optionally at the specific time of the given publishDate parameter. + pub fn publish(&self, blog_id: &str, post_id: &str) -> PostPublishCall<'a, C, NC, A> { + PostPublishCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _publish_date: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a post by ID. + pub fn delete(&self, blog_id: &str, post_id: &str) -> PostDeleteCall<'a, C, NC, A> { + PostDeleteCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Revert a published or scheduled post to draft state. + pub fn revert(&self, blog_id: &str, post_id: &str) -> PostRevertCall<'a, C, NC, A> { + PostRevertCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Search for a post. + pub fn search(&self, blog_id: &str, q: &str) -> PostSearchCall<'a, C, NC, A> { + PostSearchCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _q: q.to_string(), + _order_by: Default::default(), + _fetch_bodies: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update a post. This method supports patch semantics. + pub fn patch(&self, request: &Post, blog_id: &str, post_id: &str) -> PostPatchCall<'a, C, NC, A> { + PostPatchCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _revert: Default::default(), + _publish: Default::default(), + _max_comments: Default::default(), + _fetch_images: Default::default(), + _fetch_body: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of posts, possibly filtered. + pub fn list(&self, blog_id: &str) -> PostListCall<'a, C, NC, A> { + PostListCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _view: Default::default(), + _status: Default::default(), + _start_date: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _labels: Default::default(), + _fetch_images: Default::default(), + _fetch_bodies: Default::default(), + _end_date: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *comment* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `approve(...)`, `delete(...)`, `get(...)`, `list(...)`, `list_by_blog(...)`, `mark_as_spam(...)` and `remove_content(...)` +/// // to build up your call. +/// let rb = hub.comments(); +/// # } +/// ``` +pub struct CommentMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CommentMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one comment by ID. + pub fn get(&self, blog_id: &str, post_id: &str, comment_id: &str) -> CommentGetCall<'a, C, NC, A> { + CommentGetCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _comment_id: comment_id.to_string(), + _view: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes the content of a comment. + pub fn remove_content(&self, blog_id: &str, post_id: &str, comment_id: &str) -> CommentRemoveContentCall<'a, C, NC, A> { + CommentRemoveContentCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the comments for a blog, across all posts, possibly filtered. + pub fn list_by_blog(&self, blog_id: &str) -> CommentListByBlogCall<'a, C, NC, A> { + CommentListByBlogCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _status: Default::default(), + _start_date: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _fetch_bodies: Default::default(), + _end_date: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks a comment as spam. + pub fn mark_as_spam(&self, blog_id: &str, post_id: &str, comment_id: &str) -> CommentMarkAsSpamCall<'a, C, NC, A> { + CommentMarkAsSpamCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the comments for a post, possibly filtered. + pub fn list(&self, blog_id: &str, post_id: &str) -> CommentListCall<'a, C, NC, A> { + CommentListCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _view: Default::default(), + _status: Default::default(), + _start_date: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _fetch_bodies: Default::default(), + _end_date: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks a comment as not spam. + pub fn approve(&self, blog_id: &str, post_id: &str, comment_id: &str) -> CommentApproveCall<'a, C, NC, A> { + CommentApproveCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a comment by ID. + pub fn delete(&self, blog_id: &str, post_id: &str, comment_id: &str) -> CommentDeleteCall<'a, C, NC, A> { + CommentDeleteCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *postUserInfo* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.post_user_infos(); +/// # } +/// ``` +pub struct PostUserInfoMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PostUserInfoMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostUserInfoMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one post and user info pair, by post ID and user ID. The post user info contains per-user information about the post, such as access rights, specific to the user. + pub fn get(&self, user_id: &str, blog_id: &str, post_id: &str) -> PostUserInfoGetCall<'a, C, NC, A> { + PostUserInfoGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _blog_id: blog_id.to_string(), + _post_id: post_id.to_string(), + _max_comments: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of post and post user info pairs, possibly filtered. The post user info contains per-user information about the post, such as access rights, specific to the user. + pub fn list(&self, user_id: &str, blog_id: &str) -> PostUserInfoListCall<'a, C, NC, A> { + PostUserInfoListCall { + hub: self.hub, + _user_id: user_id.to_string(), + _blog_id: blog_id.to_string(), + _view: Default::default(), + _status: Default::default(), + _start_date: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _labels: Default::default(), + _fetch_bodies: Default::default(), + _end_date: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *blogUserInfo* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.blog_user_infos(); +/// # } +/// ``` +pub struct BlogUserInfoMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BlogUserInfoMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogUserInfoMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one blog and user info pair by blogId and userId. + pub fn get(&self, user_id: &str, blog_id: &str) -> BlogUserInfoGetCall<'a, C, NC, A> { + BlogUserInfoGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _blog_id: blog_id.to_string(), + _max_posts: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *page* resources. +/// It is not used directly, but through the `Blogger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-blogger3" as blogger3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use blogger3::Blogger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `publish(...)`, `revert(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.pages(); +/// # } +/// ``` +pub struct PageMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PageMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one blog page by ID. + pub fn get(&self, blog_id: &str, page_id: &str) -> PageGetCall<'a, C, NC, A> { + PageGetCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _view: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the pages for a blog, optionally including non-LIVE statuses. + pub fn list(&self, blog_id: &str) -> PageListCall<'a, C, NC, A> { + PageListCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _view: Default::default(), + _status: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _fetch_bodies: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Revert a published or scheduled page to draft state. + pub fn revert(&self, blog_id: &str, page_id: &str) -> PageRevertCall<'a, C, NC, A> { + PageRevertCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add a page. + pub fn insert(&self, request: &Page, blog_id: &str) -> PageInsertCall<'a, C, NC, A> { + PageInsertCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _is_draft: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update a page. This method supports patch semantics. + pub fn patch(&self, request: &Page, blog_id: &str, page_id: &str) -> PagePatchCall<'a, C, NC, A> { + PagePatchCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _revert: Default::default(), + _publish: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Publishes a draft page. + pub fn publish(&self, blog_id: &str, page_id: &str) -> PagePublishCall<'a, C, NC, A> { + PagePublishCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update a page. + pub fn update(&self, request: &Page, blog_id: &str, page_id: &str) -> PageUpdateCall<'a, C, NC, A> { + PageUpdateCall { + hub: self.hub, + _request: request.clone(), + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _revert: Default::default(), + _publish: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a page by ID. + pub fn delete(&self, blog_id: &str, page_id: &str) -> PageDeleteCall<'a, C, NC, A> { + PageDeleteCall { + hub: self.hub, + _blog_id: blog_id.to_string(), + _page_id: page_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Retrieve pageview stats for a Blog. +/// +/// A builder for the *get* method supported by a *pageView* resource. +/// It is not used directly, but through a `PageViewMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.page_views().get("blogId") +/// .add_range("erat") +/// .doit(); +/// # } +/// ``` +pub struct PageViewGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _range: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageViewGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageViewGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Pageviews)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pageViews.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if self._range.len() > 0 { + let mut s = String::new(); + for f in self._range.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("range", s)); + } + for &field in ["alt", "blogId", "range"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pageviews".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog to get. + pub fn blog_id(mut self, new_value: &str) -> PageViewGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Append the given value to the *range* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + pub fn add_range(mut self, new_value: &str) -> PageViewGetCall<'a, C, NC, A> { + self._range.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageViewGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageViewGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageViewGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one user by ID. +/// +/// A builder for the *get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().get("userId") +/// .doit(); +/// # } +/// ``` +pub struct UserGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, User)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.users.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/users/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the user to get. + pub fn user_id(mut self, new_value: &str) -> UserGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of blogs, possibly filtered. +/// +/// A builder for the *listByUser* method supported by a *blog* resource. +/// It is not used directly, but through a `BlogMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.blogs().list_by_user("userId") +/// .view("eirmod") +/// .add_status("elitr") +/// .add_role("amet") +/// .fetch_user_info(false) +/// .doit(); +/// # } +/// ``` +pub struct BlogListByUserCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _user_id: String, + _view: Option, + _status: Vec, + _role: Vec, + _fetch_user_info: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BlogListByUserCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogListByUserCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BlogList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.blogs.listByUser", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if self._role.len() > 0 { + let mut s = String::new(); + for f in self._role.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("role", s)); + } + if let Some(value) = self._fetch_user_info { + params.push(("fetchUserInfo", value.to_string())); + } + for &field in ["alt", "userId", "view", "status", "role", "fetchUserInfo"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/users/{userId}/blogs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. + pub fn user_id(mut self, new_value: &str) -> BlogListByUserCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the blogs. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> BlogListByUserCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Blog statuses to include in the result (default: Live blogs only). Note that ADMIN access is required to view deleted blogs. + pub fn add_status(mut self, new_value: &str) -> BlogListByUserCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Append the given value to the *role* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// User access types for blogs to include in the results, e.g. AUTHOR will return blogs where the user has author level access. If no roles are specified, defaults to ADMIN and AUTHOR roles. + pub fn add_role(mut self, new_value: &str) -> BlogListByUserCall<'a, C, NC, A> { + self._role.push(new_value.to_string()); + self + } + /// Sets the *fetch user info* query property to the given value. + /// + /// + /// Whether the response is a list of blogs with per-user information instead of just blogs. + pub fn fetch_user_info(mut self, new_value: bool) -> BlogListByUserCall<'a, C, NC, A> { + self._fetch_user_info = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BlogListByUserCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BlogListByUserCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BlogListByUserCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one blog by ID. +/// +/// A builder for the *get* method supported by a *blog* resource. +/// It is not used directly, but through a `BlogMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.blogs().get("blogId") +/// .view("eirmod") +/// .max_posts(68) +/// .doit(); +/// # } +/// ``` +pub struct BlogGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _view: Option, + _max_posts: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BlogGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Blog)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.blogs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if let Some(value) = self._max_posts { + params.push(("maxPosts", value.to_string())); + } + for &field in ["alt", "blogId", "view", "maxPosts"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog to get. + pub fn blog_id(mut self, new_value: &str) -> BlogGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the blog. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> BlogGetCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *max posts* query property to the given value. + /// + /// + /// Maximum number of posts to pull back with the blog. + pub fn max_posts(mut self, new_value: u32) -> BlogGetCall<'a, C, NC, A> { + self._max_posts = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BlogGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BlogGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BlogGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve a Blog by URL. +/// +/// A builder for the *getByUrl* method supported by a *blog* resource. +/// It is not used directly, but through a `BlogMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.blogs().get_by_url("url") +/// .view("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct BlogGetByUrlCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _url: String, + _view: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BlogGetByUrlCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogGetByUrlCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Blog)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.blogs.getByUrl", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("url", self._url.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + for &field in ["alt", "url", "view"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/byurl".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *url* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The URL of the blog to retrieve. + pub fn url(mut self, new_value: &str) -> BlogGetByUrlCall<'a, C, NC, A> { + self._url = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the blog. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> BlogGetByUrlCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BlogGetByUrlCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BlogGetByUrlCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BlogGetByUrlCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a post. +/// +/// A builder for the *update* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Post; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Post = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().update(&req, "blogId", "postId") +/// .revert(true) +/// .publish(true) +/// .max_comments(31) +/// .fetch_images(true) +/// .fetch_body(true) +/// .doit(); +/// # } +/// ``` +pub struct PostUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Post, + _blog_id: String, + _post_id: String, + _revert: Option, + _publish: Option, + _max_comments: Option, + _fetch_images: Option, + _fetch_body: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._revert { + params.push(("revert", value.to_string())); + } + if let Some(value) = self._publish { + params.push(("publish", value.to_string())); + } + if let Some(value) = self._max_comments { + params.push(("maxComments", value.to_string())); + } + if let Some(value) = self._fetch_images { + params.push(("fetchImages", value.to_string())); + } + if let Some(value) = self._fetch_body { + params.push(("fetchBody", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "revert", "publish", "maxComments", "fetchImages", "fetchBody"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Post) -> PostUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PostUpdateCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> PostUpdateCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *revert* query property to the given value. + /// + /// + /// Whether a revert action should be performed when the post is updated (default: false). + pub fn revert(mut self, new_value: bool) -> PostUpdateCall<'a, C, NC, A> { + self._revert = Some(new_value); + self + } + /// Sets the *publish* query property to the given value. + /// + /// + /// Whether a publish action should be performed when the post is updated (default: false). + pub fn publish(mut self, new_value: bool) -> PostUpdateCall<'a, C, NC, A> { + self._publish = Some(new_value); + self + } + /// Sets the *max comments* query property to the given value. + /// + /// + /// Maximum number of comments to retrieve with the returned post. + pub fn max_comments(mut self, new_value: u32) -> PostUpdateCall<'a, C, NC, A> { + self._max_comments = Some(new_value); + self + } + /// Sets the *fetch images* query property to the given value. + /// + /// + /// Whether image URL metadata for each post is included in the returned result (default: false). + pub fn fetch_images(mut self, new_value: bool) -> PostUpdateCall<'a, C, NC, A> { + self._fetch_images = Some(new_value); + self + } + /// Sets the *fetch body* query property to the given value. + /// + /// + /// Whether the body content of the post is included with the result (default: true). + pub fn fetch_body(mut self, new_value: bool) -> PostUpdateCall<'a, C, NC, A> { + self._fetch_body = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve a Post by Path. +/// +/// A builder for the *getByPath* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().get_by_path("blogId", "path") +/// .view("amet") +/// .max_comments(78) +/// .doit(); +/// # } +/// ``` +pub struct PostGetByPathCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _path: String, + _view: Option, + _max_comments: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostGetByPathCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostGetByPathCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.getByPath", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("path", self._path.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if let Some(value) = self._max_comments { + params.push(("maxComments", value.to_string())); + } + for &field in ["alt", "blogId", "path", "view", "maxComments"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/bypath".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch the post from. + pub fn blog_id(mut self, new_value: &str) -> PostGetByPathCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *path* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Path of the Post to retrieve. + pub fn path(mut self, new_value: &str) -> PostGetByPathCall<'a, C, NC, A> { + self._path = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> PostGetByPathCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *max comments* query property to the given value. + /// + /// + /// Maximum number of comments to pull back on a post. + pub fn max_comments(mut self, new_value: u32) -> PostGetByPathCall<'a, C, NC, A> { + self._max_comments = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostGetByPathCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostGetByPathCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostGetByPathCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Get a post by ID. +/// +/// A builder for the *get* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().get("blogId", "postId") +/// .view("ea") +/// .max_comments(21) +/// .fetch_images(true) +/// .fetch_body(true) +/// .doit(); +/// # } +/// ``` +pub struct PostGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _view: Option, + _max_comments: Option, + _fetch_images: Option, + _fetch_body: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if let Some(value) = self._max_comments { + params.push(("maxComments", value.to_string())); + } + if let Some(value) = self._fetch_images { + params.push(("fetchImages", value.to_string())); + } + if let Some(value) = self._fetch_body { + params.push(("fetchBody", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "view", "maxComments", "fetchImages", "fetchBody"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch the post from. + pub fn blog_id(mut self, new_value: &str) -> PostGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the post + pub fn post_id(mut self, new_value: &str) -> PostGetCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> PostGetCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *max comments* query property to the given value. + /// + /// + /// Maximum number of comments to pull back on a post. + pub fn max_comments(mut self, new_value: u32) -> PostGetCall<'a, C, NC, A> { + self._max_comments = Some(new_value); + self + } + /// Sets the *fetch images* query property to the given value. + /// + /// + /// Whether image URL metadata for each post is included (default: false). + pub fn fetch_images(mut self, new_value: bool) -> PostGetCall<'a, C, NC, A> { + self._fetch_images = Some(new_value); + self + } + /// Sets the *fetch body* query property to the given value. + /// + /// + /// Whether the body content of the post is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic. + pub fn fetch_body(mut self, new_value: bool) -> PostGetCall<'a, C, NC, A> { + self._fetch_body = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a post. +/// +/// A builder for the *insert* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Post; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Post = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().insert(&req, "blogId") +/// .is_draft(true) +/// .fetch_images(false) +/// .fetch_body(false) +/// .doit(); +/// # } +/// ``` +pub struct PostInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Post, + _blog_id: String, + _is_draft: Option, + _fetch_images: Option, + _fetch_body: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._is_draft { + params.push(("isDraft", value.to_string())); + } + if let Some(value) = self._fetch_images { + params.push(("fetchImages", value.to_string())); + } + if let Some(value) = self._fetch_body { + params.push(("fetchBody", value.to_string())); + } + for &field in ["alt", "blogId", "isDraft", "fetchImages", "fetchBody"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Post) -> PostInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to add the post to. + pub fn blog_id(mut self, new_value: &str) -> PostInsertCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *is draft* query property to the given value. + /// + /// + /// Whether to create the post as a draft (default: false). + pub fn is_draft(mut self, new_value: bool) -> PostInsertCall<'a, C, NC, A> { + self._is_draft = Some(new_value); + self + } + /// Sets the *fetch images* query property to the given value. + /// + /// + /// Whether image URL metadata for each post is included in the returned result (default: false). + pub fn fetch_images(mut self, new_value: bool) -> PostInsertCall<'a, C, NC, A> { + self._fetch_images = Some(new_value); + self + } + /// Sets the *fetch body* query property to the given value. + /// + /// + /// Whether the body content of the post is included with the result (default: true). + pub fn fetch_body(mut self, new_value: bool) -> PostInsertCall<'a, C, NC, A> { + self._fetch_body = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Publishes a draft post, optionally at the specific time of the given publishDate parameter. +/// +/// A builder for the *publish* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().publish("blogId", "postId") +/// .publish_date("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct PostPublishCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _publish_date: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostPublishCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostPublishCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.publish", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._publish_date { + params.push(("publishDate", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "publishDate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/publish".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PostPublishCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> PostPublishCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *publish date* query property to the given value. + /// + /// + /// Optional date and time to schedule the publishing of the Blog. If no publishDate parameter is given, the post is either published at the a previously saved schedule date (if present), or the current time. If a future date is given, the post will be scheduled to be published. + pub fn publish_date(mut self, new_value: &str) -> PostPublishCall<'a, C, NC, A> { + self._publish_date = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostPublishCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostPublishCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostPublishCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a post by ID. +/// +/// A builder for the *delete* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().delete("blogId", "postId") +/// .doit(); +/// # } +/// ``` +pub struct PostDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + for &field in ["blogId", "postId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PostDeleteCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> PostDeleteCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Revert a published or scheduled post to draft state. +/// +/// A builder for the *revert* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().revert("blogId", "postId") +/// .doit(); +/// # } +/// ``` +pub struct PostRevertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostRevertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostRevertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.revert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + for &field in ["alt", "blogId", "postId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/revert".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PostRevertCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> PostRevertCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostRevertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostRevertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostRevertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Search for a post. +/// +/// A builder for the *search* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().search("blogId", "q") +/// .order_by("sadipscing") +/// .fetch_bodies(false) +/// .doit(); +/// # } +/// ``` +pub struct PostSearchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _q: String, + _order_by: Option, + _fetch_bodies: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostSearchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostSearchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.search", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("q", self._q.to_string())); + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + for &field in ["alt", "blogId", "q", "orderBy", "fetchBodies"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/search".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch the post from. + pub fn blog_id(mut self, new_value: &str) -> PostSearchCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *q* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query terms to search this blog for matching posts. + pub fn q(mut self, new_value: &str) -> PostSearchCall<'a, C, NC, A> { + self._q = new_value.to_string(); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Sort search results + pub fn order_by(mut self, new_value: &str) -> PostSearchCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic. + pub fn fetch_bodies(mut self, new_value: bool) -> PostSearchCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostSearchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostSearchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostSearchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a post. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Post; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Post = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().patch(&req, "blogId", "postId") +/// .revert(false) +/// .publish(false) +/// .max_comments(82) +/// .fetch_images(false) +/// .fetch_body(true) +/// .doit(); +/// # } +/// ``` +pub struct PostPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Post, + _blog_id: String, + _post_id: String, + _revert: Option, + _publish: Option, + _max_comments: Option, + _fetch_images: Option, + _fetch_body: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Post)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._revert { + params.push(("revert", value.to_string())); + } + if let Some(value) = self._publish { + params.push(("publish", value.to_string())); + } + if let Some(value) = self._max_comments { + params.push(("maxComments", value.to_string())); + } + if let Some(value) = self._fetch_images { + params.push(("fetchImages", value.to_string())); + } + if let Some(value) = self._fetch_body { + params.push(("fetchBody", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "revert", "publish", "maxComments", "fetchImages", "fetchBody"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Post) -> PostPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PostPatchCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> PostPatchCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *revert* query property to the given value. + /// + /// + /// Whether a revert action should be performed when the post is updated (default: false). + pub fn revert(mut self, new_value: bool) -> PostPatchCall<'a, C, NC, A> { + self._revert = Some(new_value); + self + } + /// Sets the *publish* query property to the given value. + /// + /// + /// Whether a publish action should be performed when the post is updated (default: false). + pub fn publish(mut self, new_value: bool) -> PostPatchCall<'a, C, NC, A> { + self._publish = Some(new_value); + self + } + /// Sets the *max comments* query property to the given value. + /// + /// + /// Maximum number of comments to retrieve with the returned post. + pub fn max_comments(mut self, new_value: u32) -> PostPatchCall<'a, C, NC, A> { + self._max_comments = Some(new_value); + self + } + /// Sets the *fetch images* query property to the given value. + /// + /// + /// Whether image URL metadata for each post is included in the returned result (default: false). + pub fn fetch_images(mut self, new_value: bool) -> PostPatchCall<'a, C, NC, A> { + self._fetch_images = Some(new_value); + self + } + /// Sets the *fetch body* query property to the given value. + /// + /// + /// Whether the body content of the post is included with the result (default: true). + pub fn fetch_body(mut self, new_value: bool) -> PostPatchCall<'a, C, NC, A> { + self._fetch_body = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of posts, possibly filtered. +/// +/// A builder for the *list* method supported by a *post* resource. +/// It is not used directly, but through a `PostMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.posts().list("blogId") +/// .view("clita") +/// .add_status("consetetur") +/// .start_date("takimata") +/// .page_token("nonumy") +/// .order_by("kasd") +/// .max_results(94) +/// .labels("takimata") +/// .fetch_images(true) +/// .fetch_bodies(false) +/// .end_date("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct PostListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _view: Option, + _status: Vec, + _start_date: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _labels: Option, + _fetch_images: Option, + _fetch_bodies: Option, + _end_date: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.posts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if let Some(value) = self._start_date { + params.push(("startDate", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._labels { + params.push(("labels", value.to_string())); + } + if let Some(value) = self._fetch_images { + params.push(("fetchImages", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + if let Some(value) = self._end_date { + params.push(("endDate", value.to_string())); + } + for &field in ["alt", "blogId", "view", "status", "startDate", "pageToken", "orderBy", "maxResults", "labels", "fetchImages", "fetchBodies", "endDate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch posts from. + pub fn blog_id(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require escalated access. + pub fn view(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Statuses to include in the results. + pub fn add_status(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Sets the *start date* query property to the given value. + /// + /// + /// Earliest post date to fetch, a date-time with RFC 3339 formatting. + pub fn start_date(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._start_date = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token if the request is paged. + pub fn page_token(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Sort search results + pub fn order_by(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of posts to fetch. + pub fn max_results(mut self, new_value: u32) -> PostListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *labels* query property to the given value. + /// + /// + /// Comma-separated list of labels to search for. + pub fn labels(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._labels = Some(new_value.to_string()); + self + } + /// Sets the *fetch images* query property to the given value. + /// + /// + /// Whether image URL metadata for each post is included. + pub fn fetch_images(mut self, new_value: bool) -> PostListCall<'a, C, NC, A> { + self._fetch_images = Some(new_value); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize traffic. + pub fn fetch_bodies(mut self, new_value: bool) -> PostListCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *end date* query property to the given value. + /// + /// + /// Latest post date to fetch, a date-time with RFC 3339 formatting. + pub fn end_date(mut self, new_value: &str) -> PostListCall<'a, C, NC, A> { + self._end_date = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one comment by ID. +/// +/// A builder for the *get* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().get("blogId", "postId", "commentId") +/// .view("dolore") +/// .doit(); +/// # } +/// ``` +pub struct CommentGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _comment_id: String, + _view: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "commentId", "view"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["blogId", "postId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to containing the comment. + pub fn blog_id(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the post to fetch posts from. + pub fn post_id(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment to get. + pub fn comment_id(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level for the requested comment (default: READER). Note that some comments will require elevated permissions, for example comments where the parent posts which is in a draft state, or comments that are pending moderation. + pub fn view(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes the content of a comment. +/// +/// A builder for the *removeContent* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().remove_content("blogId", "postId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentRemoveContentCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentRemoveContentCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentRemoveContentCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.removeContent", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "blogId", "postId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/removecontent".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["blogId", "postId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> CommentRemoveContentCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> CommentRemoveContentCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment to delete content from. + pub fn comment_id(mut self, new_value: &str) -> CommentRemoveContentCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentRemoveContentCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentRemoveContentCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentRemoveContentCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the comments for a blog, across all posts, possibly filtered. +/// +/// A builder for the *listByBlog* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().list_by_blog("blogId") +/// .add_status("eirmod") +/// .start_date("consetetur") +/// .page_token("labore") +/// .max_results(71) +/// .fetch_bodies(true) +/// .end_date("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct CommentListByBlogCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _status: Vec, + _start_date: Option, + _page_token: Option, + _max_results: Option, + _fetch_bodies: Option, + _end_date: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentListByBlogCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentListByBlogCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.listByBlog", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if let Some(value) = self._start_date { + params.push(("startDate", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + if let Some(value) = self._end_date { + params.push(("endDate", value.to_string())); + } + for &field in ["alt", "blogId", "status", "startDate", "pageToken", "maxResults", "fetchBodies", "endDate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/comments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch comments from. + pub fn blog_id(mut self, new_value: &str) -> CommentListByBlogCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + pub fn add_status(mut self, new_value: &str) -> CommentListByBlogCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Sets the *start date* query property to the given value. + /// + /// + /// Earliest date of comment to fetch, a date-time with RFC 3339 formatting. + pub fn start_date(mut self, new_value: &str) -> CommentListByBlogCall<'a, C, NC, A> { + self._start_date = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token if request is paged. + pub fn page_token(mut self, new_value: &str) -> CommentListByBlogCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of comments to include in the result. + pub fn max_results(mut self, new_value: u32) -> CommentListByBlogCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether the body content of the comments is included. + pub fn fetch_bodies(mut self, new_value: bool) -> CommentListByBlogCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *end date* query property to the given value. + /// + /// + /// Latest date of comment to fetch, a date-time with RFC 3339 formatting. + pub fn end_date(mut self, new_value: &str) -> CommentListByBlogCall<'a, C, NC, A> { + self._end_date = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentListByBlogCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentListByBlogCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentListByBlogCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Marks a comment as spam. +/// +/// A builder for the *markAsSpam* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().mark_as_spam("blogId", "postId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentMarkAsSpamCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentMarkAsSpamCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentMarkAsSpamCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.markAsSpam", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "blogId", "postId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/spam".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["blogId", "postId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> CommentMarkAsSpamCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> CommentMarkAsSpamCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment to mark as spam. + pub fn comment_id(mut self, new_value: &str) -> CommentMarkAsSpamCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentMarkAsSpamCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentMarkAsSpamCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentMarkAsSpamCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the comments for a post, possibly filtered. +/// +/// A builder for the *list* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().list("blogId", "postId") +/// .view("ipsum") +/// .add_status("aliquyam") +/// .start_date("dolores") +/// .page_token("sit") +/// .max_results(60) +/// .fetch_bodies(true) +/// .end_date("justo") +/// .doit(); +/// # } +/// ``` +pub struct CommentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _view: Option, + _status: Vec, + _start_date: Option, + _page_token: Option, + _max_results: Option, + _fetch_bodies: Option, + _end_date: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if let Some(value) = self._start_date { + params.push(("startDate", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + if let Some(value) = self._end_date { + params.push(("endDate", value.to_string())); + } + for &field in ["alt", "blogId", "postId", "view", "status", "startDate", "pageToken", "maxResults", "fetchBodies", "endDate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch comments from. + pub fn blog_id(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the post to fetch posts from. + pub fn post_id(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + pub fn add_status(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Sets the *start date* query property to the given value. + /// + /// + /// Earliest date of comment to fetch, a date-time with RFC 3339 formatting. + pub fn start_date(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._start_date = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token if request is paged. + pub fn page_token(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of comments to include in the result. + pub fn max_results(mut self, new_value: u32) -> CommentListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether the body content of the comments is included. + pub fn fetch_bodies(mut self, new_value: bool) -> CommentListCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *end date* query property to the given value. + /// + /// + /// Latest date of comment to fetch, a date-time with RFC 3339 formatting. + pub fn end_date(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._end_date = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Marks a comment as not spam. +/// +/// A builder for the *approve* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().approve("blogId", "postId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentApproveCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentApproveCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentApproveCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.approve", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "blogId", "postId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments/{commentId}/approve".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["blogId", "postId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> CommentApproveCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> CommentApproveCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment to mark as not spam. + pub fn comment_id(mut self, new_value: &str) -> CommentApproveCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentApproveCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentApproveCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentApproveCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a comment by ID. +/// +/// A builder for the *delete* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().delete("blogId", "postId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _post_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.comments.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["blogId", "postId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/posts/{postId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{postId}", "postId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["blogId", "postId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> CommentDeleteCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Post. + pub fn post_id(mut self, new_value: &str) -> CommentDeleteCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment to delete. + pub fn comment_id(mut self, new_value: &str) -> CommentDeleteCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one post and user info pair, by post ID and user ID. The post user info contains per-user information about the post, such as access rights, specific to the user. +/// +/// A builder for the *get* method supported by a *postUserInfo* resource. +/// It is not used directly, but through a `PostUserInfoMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.post_user_infos().get("userId", "blogId", "postId") +/// .max_comments(14) +/// .doit(); +/// # } +/// ``` +pub struct PostUserInfoGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _user_id: String, + _blog_id: String, + _post_id: String, + _max_comments: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostUserInfoGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostUserInfoGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostUserInfo)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.postUserInfos.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("postId", self._post_id.to_string())); + if let Some(value) = self._max_comments { + params.push(("maxComments", value.to_string())); + } + for &field in ["alt", "userId", "blogId", "postId", "maxComments"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/users/{userId}/blogs/{blogId}/posts/{postId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{blogId}", "blogId"), ("{postId}", "postId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["userId", "blogId", "postId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. + pub fn user_id(mut self, new_value: &str) -> PostUserInfoGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog. + pub fn blog_id(mut self, new_value: &str) -> PostUserInfoGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *post id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the post to get. + pub fn post_id(mut self, new_value: &str) -> PostUserInfoGetCall<'a, C, NC, A> { + self._post_id = new_value.to_string(); + self + } + /// Sets the *max comments* query property to the given value. + /// + /// + /// Maximum number of comments to pull back on a post. + pub fn max_comments(mut self, new_value: u32) -> PostUserInfoGetCall<'a, C, NC, A> { + self._max_comments = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostUserInfoGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostUserInfoGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostUserInfoGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of post and post user info pairs, possibly filtered. The post user info contains per-user information about the post, such as access rights, specific to the user. +/// +/// A builder for the *list* method supported by a *postUserInfo* resource. +/// It is not used directly, but through a `PostUserInfoMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.post_user_infos().list("userId", "blogId") +/// .view("voluptua.") +/// .add_status("duo") +/// .start_date("sed") +/// .page_token("aliquyam") +/// .order_by("ea") +/// .max_results(84) +/// .labels("et") +/// .fetch_bodies(true) +/// .end_date("diam") +/// .doit(); +/// # } +/// ``` +pub struct PostUserInfoListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _user_id: String, + _blog_id: String, + _view: Option, + _status: Vec, + _start_date: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _labels: Option, + _fetch_bodies: Option, + _end_date: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostUserInfoListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostUserInfoListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostUserInfosList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.postUserInfos.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if let Some(value) = self._start_date { + params.push(("startDate", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._labels { + params.push(("labels", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + if let Some(value) = self._end_date { + params.push(("endDate", value.to_string())); + } + for &field in ["alt", "userId", "blogId", "view", "status", "startDate", "pageToken", "orderBy", "maxResults", "labels", "fetchBodies", "endDate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/users/{userId}/blogs/{blogId}/posts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. + pub fn user_id(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch posts from. + pub fn blog_id(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + pub fn add_status(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Sets the *start date* query property to the given value. + /// + /// + /// Earliest post date to fetch, a date-time with RFC 3339 formatting. + pub fn start_date(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._start_date = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token if the request is paged. + pub fn page_token(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Sort order applied to search results. Default is published. + pub fn order_by(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of posts to fetch. + pub fn max_results(mut self, new_value: u32) -> PostUserInfoListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *labels* query property to the given value. + /// + /// + /// Comma-separated list of labels to search for. + pub fn labels(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._labels = Some(new_value.to_string()); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether the body content of posts is included. Default is false. + pub fn fetch_bodies(mut self, new_value: bool) -> PostUserInfoListCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *end date* query property to the given value. + /// + /// + /// Latest post date to fetch, a date-time with RFC 3339 formatting. + pub fn end_date(mut self, new_value: &str) -> PostUserInfoListCall<'a, C, NC, A> { + self._end_date = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostUserInfoListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostUserInfoListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostUserInfoListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one blog and user info pair by blogId and userId. +/// +/// A builder for the *get* method supported by a *blogUserInfo* resource. +/// It is not used directly, but through a `BlogUserInfoMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.blog_user_infos().get("userId", "blogId") +/// .max_posts(86) +/// .doit(); +/// # } +/// ``` +pub struct BlogUserInfoGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _user_id: String, + _blog_id: String, + _max_posts: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BlogUserInfoGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BlogUserInfoGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BlogUserInfo)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.blogUserInfos.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._max_posts { + params.push(("maxPosts", value.to_string())); + } + for &field in ["alt", "userId", "blogId", "maxPosts"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/users/{userId}/blogs/{blogId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. + pub fn user_id(mut self, new_value: &str) -> BlogUserInfoGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog to get. + pub fn blog_id(mut self, new_value: &str) -> BlogUserInfoGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *max posts* query property to the given value. + /// + /// + /// Maximum number of posts to pull back with the blog. + pub fn max_posts(mut self, new_value: u32) -> BlogUserInfoGetCall<'a, C, NC, A> { + self._max_posts = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BlogUserInfoGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BlogUserInfoGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BlogUserInfoGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one blog page by ID. +/// +/// A builder for the *get* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().get("blogId", "pageId") +/// .view("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct PageGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _page_id: String, + _view: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + for &field in ["alt", "blogId", "pageId", "view"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog containing the page. + pub fn blog_id(mut self, new_value: &str) -> PageGetCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the page to get. + pub fn page_id(mut self, new_value: &str) -> PageGetCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + pub fn view(mut self, new_value: &str) -> PageGetCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the pages for a blog, optionally including non-LIVE statuses. +/// +/// A builder for the *list* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().list("blogId") +/// .view("At") +/// .add_status("consetetur") +/// .page_token("et") +/// .max_results(21) +/// .fetch_bodies(true) +/// .doit(); +/// # } +/// ``` +pub struct PageListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _view: Option, + _status: Vec, + _page_token: Option, + _max_results: Option, + _fetch_bodies: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PageList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._status.len() > 0 { + let mut s = String::new(); + for f in self._status.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("status", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._fetch_bodies { + params.push(("fetchBodies", value.to_string())); + } + for &field in ["alt", "blogId", "view", "status", "pageToken", "maxResults", "fetchBodies"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to fetch Pages from. + pub fn blog_id(mut self, new_value: &str) -> PageListCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *view* query property to the given value. + /// + /// + /// Access level with which to view the returned result. Note that some fields require elevated access. + pub fn view(mut self, new_value: &str) -> PageListCall<'a, C, NC, A> { + self._view = Some(new_value.to_string()); + self + } + /// Append the given value to the *status* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + pub fn add_status(mut self, new_value: &str) -> PageListCall<'a, C, NC, A> { + self._status.push(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token if the request is paged. + pub fn page_token(mut self, new_value: &str) -> PageListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of Pages to fetch. + pub fn max_results(mut self, new_value: u32) -> PageListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *fetch bodies* query property to the given value. + /// + /// + /// Whether to retrieve the Page bodies. + pub fn fetch_bodies(mut self, new_value: bool) -> PageListCall<'a, C, NC, A> { + self._fetch_bodies = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Revert a published or scheduled page to draft state. +/// +/// A builder for the *revert* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().revert("blogId", "pageId") +/// .doit(); +/// # } +/// ``` +pub struct PageRevertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _page_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageRevertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageRevertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.revert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + for &field in ["alt", "blogId", "pageId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}/revert".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog. + pub fn blog_id(mut self, new_value: &str) -> PageRevertCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the page. + pub fn page_id(mut self, new_value: &str) -> PageRevertCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageRevertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageRevertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageRevertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Add a page. +/// +/// A builder for the *insert* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Page; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Page = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().insert(&req, "blogId") +/// .is_draft(true) +/// .doit(); +/// # } +/// ``` +pub struct PageInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Page, + _blog_id: String, + _is_draft: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + if let Some(value) = self._is_draft { + params.push(("isDraft", value.to_string())); + } + for &field in ["alt", "blogId", "isDraft"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["blogId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Page) -> PageInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the blog to add the page to. + pub fn blog_id(mut self, new_value: &str) -> PageInsertCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *is draft* query property to the given value. + /// + /// + /// Whether to create the page as a draft (default: false). + pub fn is_draft(mut self, new_value: bool) -> PageInsertCall<'a, C, NC, A> { + self._is_draft = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a page. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Page; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Page = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().patch(&req, "blogId", "pageId") +/// .revert(true) +/// .publish(true) +/// .doit(); +/// # } +/// ``` +pub struct PagePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Page, + _blog_id: String, + _page_id: String, + _revert: Option, + _publish: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PagePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PagePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + if let Some(value) = self._revert { + params.push(("revert", value.to_string())); + } + if let Some(value) = self._publish { + params.push(("publish", value.to_string())); + } + for &field in ["alt", "blogId", "pageId", "revert", "publish"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Page) -> PagePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PagePatchCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Page. + pub fn page_id(mut self, new_value: &str) -> PagePatchCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *revert* query property to the given value. + /// + /// + /// Whether a revert action should be performed when the page is updated (default: false). + pub fn revert(mut self, new_value: bool) -> PagePatchCall<'a, C, NC, A> { + self._revert = Some(new_value); + self + } + /// Sets the *publish* query property to the given value. + /// + /// + /// Whether a publish action should be performed when the page is updated (default: false). + pub fn publish(mut self, new_value: bool) -> PagePatchCall<'a, C, NC, A> { + self._publish = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PagePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PagePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PagePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Publishes a draft page. +/// +/// A builder for the *publish* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().publish("blogId", "pageId") +/// .doit(); +/// # } +/// ``` +pub struct PagePublishCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _page_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PagePublishCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PagePublishCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.publish", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + for &field in ["alt", "blogId", "pageId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}/publish".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the blog. + pub fn blog_id(mut self, new_value: &str) -> PagePublishCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the page. + pub fn page_id(mut self, new_value: &str) -> PagePublishCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PagePublishCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PagePublishCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PagePublishCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update a page. +/// +/// A builder for the *update* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// use blogger3::Page; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Page = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().update(&req, "blogId", "pageId") +/// .revert(true) +/// .publish(true) +/// .doit(); +/// # } +/// ``` +pub struct PageUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _request: Page, + _blog_id: String, + _page_id: String, + _revert: Option, + _publish: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Page)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + if let Some(value) = self._revert { + params.push(("revert", value.to_string())); + } + if let Some(value) = self._publish { + params.push(("publish", value.to_string())); + } + for &field in ["alt", "blogId", "pageId", "revert", "publish"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Page) -> PageUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PageUpdateCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Page. + pub fn page_id(mut self, new_value: &str) -> PageUpdateCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *revert* query property to the given value. + /// + /// + /// Whether a revert action should be performed when the page is updated (default: false). + pub fn revert(mut self, new_value: bool) -> PageUpdateCall<'a, C, NC, A> { + self._revert = Some(new_value); + self + } + /// Sets the *publish* query property to the given value. + /// + /// + /// Whether a publish action should be performed when the page is updated (default: false). + pub fn publish(mut self, new_value: bool) -> PageUpdateCall<'a, C, NC, A> { + self._publish = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a page by ID. +/// +/// A builder for the *delete* method supported by a *page* resource. +/// It is not used directly, but through a `PageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-blogger3" as blogger3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use blogger3::Blogger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Blogger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.pages().delete("blogId", "pageId") +/// .doit(); +/// # } +/// ``` +pub struct PageDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Blogger, + _blog_id: String, + _page_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PageDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PageDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "blogger.pages.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("blogId", self._blog_id.to_string())); + params.push(("pageId", self._page_id.to_string())); + for &field in ["blogId", "pageId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/blogger/v3/blogs/{blogId}/pages/{pageId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{blogId}", "blogId"), ("{pageId}", "pageId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["blogId", "pageId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *blog id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Blog. + pub fn blog_id(mut self, new_value: &str) -> PageDeleteCall<'a, C, NC, A> { + self._blog_id = new_value.to_string(); + self + } + /// Sets the *page id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the Page. + pub fn page_id(mut self, new_value: &str) -> PageDeleteCall<'a, C, NC, A> { + self._page_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PageDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PageDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PageDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/books1/Cargo.toml b/gen/books1/Cargo.toml new file mode 100644 index 0000000000..392a5eed02 --- /dev/null +++ b/gen/books1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-books1" +version = "0.1.0+20150309" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with books (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/books1" +homepage = "https://developers.google.com/books/docs/v1/getting_started" +documentation = "http://byron.github.io/google-apis-rs/google-books1" +license = "MIT" +keywords = ["books", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/books1/LICENSE.md b/gen/books1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/books1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/books1/README.md b/gen/books1/README.md new file mode 100644 index 0000000000..0568c3ff01 --- /dev/null +++ b/gen/books1/README.md @@ -0,0 +1,198 @@ + +The `google-books1` library allows access to all features of the *Google books* service. + +This documentation was generated from *books* crate version *0.1.0+20150309*, where *20150309* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *books* *v1* API can be found at the +[official documentation site](https://developers.google.com/books/docs/v1/getting_started). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-books1/struct.Books.html) ... + +* bookshelves + * [*get*](http://byron.github.io/google-apis-rs/google-books1/struct.BookshelveGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-books1/struct.BookshelveListCall.html) and [*volumes list*](http://byron.github.io/google-apis-rs/google-books1/struct.BookshelveVolumeListCall.html) +* cloudloading + * [*add book*](http://byron.github.io/google-apis-rs/google-books1/struct.CloudloadingAddBookCall.html), [*delete book*](http://byron.github.io/google-apis-rs/google-books1/struct.CloudloadingDeleteBookCall.html) and [*update book*](http://byron.github.io/google-apis-rs/google-books1/struct.CloudloadingUpdateBookCall.html) +* dictionary + * [*list offline metadata*](http://byron.github.io/google-apis-rs/google-books1/struct.DictionaryListOfflineMetadataCall.html) +* layers + * [*annotation data get*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerAnnotationDataGetCall.html), [*annotation data list*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerAnnotationDataListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerListCall.html), [*volume annotations get*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerVolumeAnnotationGetCall.html) and [*volume annotations list*](http://byron.github.io/google-apis-rs/google-books1/struct.LayerVolumeAnnotationListCall.html) +* myconfig + * [*get user settings*](http://byron.github.io/google-apis-rs/google-books1/struct.MyconfigGetUserSettingCall.html), [*release download access*](http://byron.github.io/google-apis-rs/google-books1/struct.MyconfigReleaseDownloadAccesCall.html), [*request access*](http://byron.github.io/google-apis-rs/google-books1/struct.MyconfigRequestAccesCall.html), [*sync volume licenses*](http://byron.github.io/google-apis-rs/google-books1/struct.MyconfigSyncVolumeLicenseCall.html) and [*update user settings*](http://byron.github.io/google-apis-rs/google-books1/struct.MyconfigUpdateUserSettingCall.html) +* mylibrary + * [*annotations delete*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryAnnotationDeleteCall.html), [*annotations insert*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryAnnotationInsertCall.html), [*annotations list*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryAnnotationListCall.html), [*annotations summary*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryAnnotationSummaryCall.html), [*annotations update*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryAnnotationUpdateCall.html), [*bookshelves add volume*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveAddVolumeCall.html), [*bookshelves clear volumes*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveClearVolumeCall.html), [*bookshelves get*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveGetCall.html), [*bookshelves list*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveListCall.html), [*bookshelves move volume*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveMoveVolumeCall.html), [*bookshelves remove volume*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveRemoveVolumeCall.html), [*bookshelves volumes list*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryBookshelveVolumeListCall.html), [*readingpositions get*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryReadingpositionGetCall.html) and [*readingpositions set position*](http://byron.github.io/google-apis-rs/google-books1/struct.MylibraryReadingpositionSetPositionCall.html) +* onboarding + * [*list categories*](http://byron.github.io/google-apis-rs/google-books1/struct.OnboardingListCategoryCall.html) and [*list category volumes*](http://byron.github.io/google-apis-rs/google-books1/struct.OnboardingListCategoryVolumeCall.html) +* promooffer + * [*accept*](http://byron.github.io/google-apis-rs/google-books1/struct.PromoofferAcceptCall.html), [*dismiss*](http://byron.github.io/google-apis-rs/google-books1/struct.PromoofferDismisCall.html) and [*get*](http://byron.github.io/google-apis-rs/google-books1/struct.PromoofferGetCall.html) +* [volumes](http://byron.github.io/google-apis-rs/google-books1/struct.Volume.html) + * [*associated list*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeAssociatedListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeListCall.html), [*mybooks list*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeMybookListCall.html), [*recommended list*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeRecommendedListCall.html), [*recommended rate*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeRecommendedRateCall.html) and [*useruploaded list*](http://byron.github.io/google-apis-rs/google-books1/struct.VolumeUseruploadedListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-books1/struct.Books.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-books1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-books1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-books1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.volumes().useruploaded_list(...).doit() +let r = hub.myconfig().sync_volume_licenses(...).doit() +let r = hub.volumes().list(...).doit() +let r = hub.volumes().associated_list(...).doit() +let r = hub.bookshelves().volumes_list(...).doit() +let r = hub.volumes().recommended_list(...).doit() +let r = hub.mylibrary().bookshelves_volumes_list(...).doit() +let r = hub.volumes().mybooks_list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-books1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-books1" as books1; +use books1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use books1::Books; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Books::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.volumes().list("q") + .start_index(53) + .source("Stet") + .show_preorders(true) + .projection("et") + .print_type("dolores") + .partner("kasd") + .order_by("accusam") + .max_results(93) + .library_restrict("justo") + .lang_restrict("amet.") + .filter("erat") + .download("labore") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-books1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-books1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-books1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-books1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-books1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-books1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-books1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-books1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-books1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-books1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-books1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-books1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-books1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **books1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/books1/src/cmn.rs b/gen/books1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/books1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/books1/src/lib.rs b/gen/books1/src/lib.rs new file mode 100644 index 0000000000..c63d9e2299 --- /dev/null +++ b/gen/books1/src/lib.rs @@ -0,0 +1,14956 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *books* crate version *0.1.0+20150309*, where *20150309* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *books* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/books/docs/v1/getting_started). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/books1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Books.html) ... +//! +//! * bookshelves +//! * [*get*](struct.BookshelveGetCall.html), [*list*](struct.BookshelveListCall.html) and [*volumes list*](struct.BookshelveVolumeListCall.html) +//! * cloudloading +//! * [*add book*](struct.CloudloadingAddBookCall.html), [*delete book*](struct.CloudloadingDeleteBookCall.html) and [*update book*](struct.CloudloadingUpdateBookCall.html) +//! * dictionary +//! * [*list offline metadata*](struct.DictionaryListOfflineMetadataCall.html) +//! * layers +//! * [*annotation data get*](struct.LayerAnnotationDataGetCall.html), [*annotation data list*](struct.LayerAnnotationDataListCall.html), [*get*](struct.LayerGetCall.html), [*list*](struct.LayerListCall.html), [*volume annotations get*](struct.LayerVolumeAnnotationGetCall.html) and [*volume annotations list*](struct.LayerVolumeAnnotationListCall.html) +//! * myconfig +//! * [*get user settings*](struct.MyconfigGetUserSettingCall.html), [*release download access*](struct.MyconfigReleaseDownloadAccesCall.html), [*request access*](struct.MyconfigRequestAccesCall.html), [*sync volume licenses*](struct.MyconfigSyncVolumeLicenseCall.html) and [*update user settings*](struct.MyconfigUpdateUserSettingCall.html) +//! * mylibrary +//! * [*annotations delete*](struct.MylibraryAnnotationDeleteCall.html), [*annotations insert*](struct.MylibraryAnnotationInsertCall.html), [*annotations list*](struct.MylibraryAnnotationListCall.html), [*annotations summary*](struct.MylibraryAnnotationSummaryCall.html), [*annotations update*](struct.MylibraryAnnotationUpdateCall.html), [*bookshelves add volume*](struct.MylibraryBookshelveAddVolumeCall.html), [*bookshelves clear volumes*](struct.MylibraryBookshelveClearVolumeCall.html), [*bookshelves get*](struct.MylibraryBookshelveGetCall.html), [*bookshelves list*](struct.MylibraryBookshelveListCall.html), [*bookshelves move volume*](struct.MylibraryBookshelveMoveVolumeCall.html), [*bookshelves remove volume*](struct.MylibraryBookshelveRemoveVolumeCall.html), [*bookshelves volumes list*](struct.MylibraryBookshelveVolumeListCall.html), [*readingpositions get*](struct.MylibraryReadingpositionGetCall.html) and [*readingpositions set position*](struct.MylibraryReadingpositionSetPositionCall.html) +//! * onboarding +//! * [*list categories*](struct.OnboardingListCategoryCall.html) and [*list category volumes*](struct.OnboardingListCategoryVolumeCall.html) +//! * promooffer +//! * [*accept*](struct.PromoofferAcceptCall.html), [*dismiss*](struct.PromoofferDismisCall.html) and [*get*](struct.PromoofferGetCall.html) +//! * [volumes](struct.Volume.html) +//! * [*associated list*](struct.VolumeAssociatedListCall.html), [*get*](struct.VolumeGetCall.html), [*list*](struct.VolumeListCall.html), [*mybooks list*](struct.VolumeMybookListCall.html), [*recommended list*](struct.VolumeRecommendedListCall.html), [*recommended rate*](struct.VolumeRecommendedRateCall.html) and [*useruploaded list*](struct.VolumeUseruploadedListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Books.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.volumes().useruploaded_list(...).doit() +//! let r = hub.myconfig().sync_volume_licenses(...).doit() +//! let r = hub.volumes().list(...).doit() +//! let r = hub.volumes().associated_list(...).doit() +//! let r = hub.bookshelves().volumes_list(...).doit() +//! let r = hub.volumes().recommended_list(...).doit() +//! let r = hub.mylibrary().bookshelves_volumes_list(...).doit() +//! let r = hub.volumes().mybooks_list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-books1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-books1" as books1; +//! use books1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use books1::Books; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Books::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.volumes().list("q") +//! .start_index(11) +//! .source("dolores") +//! .show_preorders(false) +//! .projection("sadipscing") +//! .print_type("aliquyam") +//! .partner("ea") +//! .order_by("no") +//! .max_results(80) +//! .library_restrict("justo") +//! .lang_restrict("et") +//! .filter("et") +//! .download("diam") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your books + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/books", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Books related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// use books1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().list("q") +/// .start_index(96) +/// .source("et") +/// .show_preorders(false) +/// .projection("aliquyam") +/// .print_type("sea") +/// .partner("Lorem") +/// .order_by("eos") +/// .max_results(20) +/// .library_restrict("sadipscing") +/// .lang_restrict("dolor") +/// .filter("eirmod") +/// .download("elitr") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Books { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Books {} + +impl<'a, C, NC, A> Books + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Books { + Books { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn bookshelves(&'a self) -> BookshelveMethods<'a, C, NC, A> { + BookshelveMethods { hub: &self } + } + pub fn cloudloading(&'a self) -> CloudloadingMethods<'a, C, NC, A> { + CloudloadingMethods { hub: &self } + } + pub fn dictionary(&'a self) -> DictionaryMethods<'a, C, NC, A> { + DictionaryMethods { hub: &self } + } + pub fn layers(&'a self) -> LayerMethods<'a, C, NC, A> { + LayerMethods { hub: &self } + } + pub fn myconfig(&'a self) -> MyconfigMethods<'a, C, NC, A> { + MyconfigMethods { hub: &self } + } + pub fn mylibrary(&'a self) -> MylibraryMethods<'a, C, NC, A> { + MylibraryMethods { hub: &self } + } + pub fn onboarding(&'a self) -> OnboardingMethods<'a, C, NC, A> { + OnboardingMethods { hub: &self } + } + pub fn promooffer(&'a self) -> PromoofferMethods<'a, C, NC, A> { + PromoofferMethods { hub: &self } + } + pub fn volumes(&'a self) -> VolumeMethods<'a, C, NC, A> { + VolumeMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list categories onboarding](struct.OnboardingListCategoryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Category { + /// A list of onboarding categories. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Category {} + + +/// A list of onboarding categories. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CategoryItems { + /// no description provided + #[serde(alias="badgeUrl")] + pub badge_url: String, + /// no description provided + #[serde(alias="categoryId")] + pub category_id: String, + /// no description provided + pub name: String, +} + +impl NestedType for CategoryItems {} +impl Part for CategoryItems {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ConcurrentAccessRestriction { + /// Client nonce for verification. Download access and client-validation only. + pub nonce: String, + /// Resource type. + pub kind: String, + /// Whether this volume has any concurrent access restrictions. + pub restricted: bool, + /// Identifies the volume for which this entry applies. + #[serde(alias="volumeId")] + pub volume_id: String, + /// The maximum number of concurrent access licenses for this volume. + #[serde(alias="maxConcurrentDevices")] + pub max_concurrent_devices: i32, + /// Whether access is granted for this (user, device, volume). + #[serde(alias="deviceAllowed")] + pub device_allowed: bool, + /// Client app identifier for verification. Download access and client-validation only. + pub source: String, + /// Time in seconds for license auto-expiration. + #[serde(alias="timeWindowSeconds")] + pub time_window_seconds: i32, + /// Response signature. + pub signature: String, + /// Error/warning reason code. + #[serde(alias="reasonCode")] + pub reason_code: String, + /// Error/warning message. + pub message: String, +} + +impl Part for ConcurrentAccessRestriction {} + + +/// Physical dimensions of this volume. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeVolumeInfoDimensions { + /// Width of this volume (in cm). + pub width: String, + /// Height or length of this volume (in cm). + pub height: String, + /// Thickness of this volume (in cm). + pub thickness: String, +} + +impl NestedType for VolumeVolumeInfoDimensions {} +impl Part for VolumeVolumeInfoDimensions {} + + +/// General volume information. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeVolumeInfo { + /// Volume subtitle. (In LITE projection.) + pub subtitle: String, + /// A synopsis of the volume. The text of the description is formatted in HTML and includes simple formatting elements, such as b, i, and br tags. (In LITE projection.) + pub description: String, + /// Total number of pages as per publisher metadata. + #[serde(alias="pageCount")] + pub page_count: i32, + /// A list of image links for all the sizes that are available. (In LITE projection.) + #[serde(alias="imageLinks")] + pub image_links: VolumeVolumeInfoImageLinks, + /// The number of review ratings for this volume. + #[serde(alias="ratingsCount")] + pub ratings_count: i32, + /// The main category to which this volume belongs. It will be the category from the categories list returned below that has the highest weight. + #[serde(alias="mainCategory")] + pub main_category: String, + /// The names of the authors and/or editors for this volume. (In LITE projection) + pub authors: Vec, + /// A list of subject categories, such as "Fiction", "Suspense", etc. + pub categories: Vec, + /// Publisher of this volume. (In LITE projection.) + pub publisher: String, + /// Physical dimensions of this volume. + pub dimensions: VolumeVolumeInfoDimensions, + /// Best language for this volume (based on content). It is the two-letter ISO 639-1 code such as 'fr', 'en', etc. + pub language: String, + /// URL to preview this volume on the Google Books site. + #[serde(alias="previewLink")] + pub preview_link: String, + /// The reading modes available for this volume. + #[serde(alias="readingModes")] + pub reading_modes: String, + /// Date of publication. (In LITE projection.) + #[serde(alias="publishedDate")] + pub published_date: String, + /// Type of publication of this volume. Possible values are BOOK or MAGAZINE. + #[serde(alias="printType")] + pub print_type: String, + /// Total number of sample pages as per publisher metadata. + #[serde(alias="samplePageCount")] + pub sample_page_count: i32, + /// An identifier for the version of the volume content (text & images). (In LITE projection) + #[serde(alias="contentVersion")] + pub content_version: String, + /// Total number of printed pages in generated pdf representation. + #[serde(alias="printedPageCount")] + pub printed_page_count: i32, + /// Industry standard identifiers for this volume. + #[serde(alias="industryIdentifiers")] + pub industry_identifiers: Vec, + /// Volume title. (In LITE projection.) + pub title: String, + /// The mean review rating for this volume. (min = 1.0, max = 5.0) + #[serde(alias="averageRating")] + pub average_rating: f64, + /// URL to view information about this volume on the Google Books site. (In LITE projection) + #[serde(alias="infoLink")] + pub info_link: String, + /// Canonical URL for a volume. (In LITE projection.) + #[serde(alias="canonicalVolumeLink")] + pub canonical_volume_link: String, +} + +impl NestedType for VolumeVolumeInfo {} +impl Part for VolumeVolumeInfo {} + + +/// Selection ranges sent from the client. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AnnotationClientVersionRanges { + /// Range in image CFI format for this annotation sent by client. + #[serde(alias="imageCfiRange")] + pub image_cfi_range: BooksAnnotationsRange, + /// Range in GB text format for this annotation sent by client. + #[serde(alias="gbTextRange")] + pub gb_text_range: BooksAnnotationsRange, + /// Content version the client sent in. + #[serde(alias="contentVersion")] + pub content_version: String, + /// Range in CFI format for this annotation sent by client. + #[serde(alias="cfiRange")] + pub cfi_range: BooksAnnotationsRange, + /// Range in GB image format for this annotation sent by client. + #[serde(alias="gbImageRange")] + pub gb_image_range: BooksAnnotationsRange, +} + +impl NestedType for AnnotationClientVersionRanges {} +impl Part for AnnotationClientVersionRanges {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [request access myconfig](struct.MyconfigRequestAccesCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RequestAccess { + /// A download access response. + #[serde(alias="downloadAccess")] + pub download_access: DownloadAccessRestriction, + /// Resource type. + pub kind: String, + /// A concurrent access response. + #[serde(alias="concurrentAccess")] + pub concurrent_access: ConcurrentAccessRestriction, +} + +impl ResponseResult for RequestAccess {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OffersItemsItems { + /// no description provided + pub description: String, + /// no description provided + pub author: String, + /// no description provided + pub title: String, + /// no description provided + #[serde(alias="coverUrl")] + pub cover_url: String, + /// no description provided + #[serde(alias="volumeId")] + pub volume_id: String, + /// no description provided + #[serde(alias="canonicalVolumeLink")] + pub canonical_volume_link: String, +} + +impl NestedType for OffersItemsItems {} +impl Part for OffersItemsItems {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [annotations list mylibrary](struct.MylibraryAnnotationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Annotations { + /// Token to pass in for pagination for the next page. This will not be present if this request does not have more results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of annotations. + pub items: Vec, + /// Resource type. + pub kind: String, + /// Total number of annotations found. This may be greater than the number of notes returned in this response if results have been paginated. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for Annotations {} + + +/// Offers available for this volume (sales and rentals). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoOffers { + /// The rental duration (for rental offers only). + #[serde(alias="rentalDuration")] + pub rental_duration: VolumeSaleInfoOffersRentalDuration, + /// Offer retail (=discounted) price in Micros + #[serde(alias="retailPrice")] + pub retail_price: VolumeSaleInfoOffersRetailPrice, + /// Offer list (=undiscounted) price in Micros. + #[serde(alias="listPrice")] + pub list_price: VolumeSaleInfoOffersListPrice, + /// The finsky offer type (e.g., PURCHASE=0 RENTAL=3) + #[serde(alias="finskyOfferType")] + pub finsky_offer_type: i32, +} + +impl NestedType for VolumeSaleInfoOffers {} +impl Part for VolumeSaleInfoOffers {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list offline metadata dictionary](struct.DictionaryListOfflineMetadataCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Metadata { + /// A list of offline dictionary metadata. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Metadata {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [useruploaded list volumes](struct.VolumeUseruploadedListCall.html) (none) +/// * [recommended rate volumes](struct.VolumeRecommendedRateCall.html) (none) +/// * [list volumes](struct.VolumeListCall.html) (none) +/// * [associated list volumes](struct.VolumeAssociatedListCall.html) (none) +/// * [get volumes](struct.VolumeGetCall.html) (response) +/// * [recommended list volumes](struct.VolumeRecommendedListCall.html) (none) +/// * [mybooks list volumes](struct.VolumeMybookListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Volume { + /// Resource type for a volume. (In LITE projection.) + pub kind: String, + /// Any information about a volume related to reading or obtaining that volume text. This information can depend on country (books may be public domain in one country but not in another, e.g.). + #[serde(alias="accessInfo")] + pub access_info: VolumeAccessInfo, + /// Search result information related to this volume. + #[serde(alias="searchInfo")] + pub search_info: VolumeSearchInfo, + /// Any information about a volume related to the eBookstore and/or purchaseability. This information can depend on the country where the request originates from (i.e. books may not be for sale in certain countries). + #[serde(alias="saleInfo")] + pub sale_info: VolumeSaleInfo, + /// Opaque identifier for a specific version of a volume resource. (In LITE projection) + pub etag: String, + /// What layers exist in this volume and high level information about them. + #[serde(alias="layerInfo")] + pub layer_info: VolumeLayerInfo, + /// General volume information. + #[serde(alias="volumeInfo")] + pub volume_info: VolumeVolumeInfo, + /// Recommendation related information for this volume. + #[serde(alias="recommendedInfo")] + pub recommended_info: VolumeRecommendedInfo, + /// Unique identifier for a volume. (In LITE projection.) + pub id: String, + /// URL to this resource. (In LITE projection.) + #[serde(alias="selfLink")] + pub self_link: String, + /// User specific information related to this volume. (e.g. page this user last read or whether they purchased this book) + #[serde(alias="userInfo")] + pub user_info: VolumeUserInfo, +} + +impl Resource for Volume {} +impl ResponseResult for Volume {} + + +/// What layers exist in this volume and high level information about them. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeLayerInfo { + /// A layer should appear here if and only if the layer exists for this book. + pub layers: Vec, +} + +impl NestedType for VolumeLayerInfo {} +impl Part for VolumeLayerInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get user settings myconfig](struct.MyconfigGetUserSettingCall.html) (response) +/// * [update user settings myconfig](struct.MyconfigUpdateUserSettingCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Usersettings { + /// Resource type. + pub kind: Option, + /// User settings in sub-objects, each for different purposes. + #[serde(alias="notesExport")] + pub notes_export: Option, +} + +impl RequestValue for Usersettings {} +impl ResponseResult for Usersettings {} + + +/// Recommendation related information for this volume. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeRecommendedInfo { + /// A text explaining why this volume is recommended. + pub explanation: String, +} + +impl NestedType for VolumeRecommendedInfo {} +impl Part for VolumeRecommendedInfo {} + + +/// A list of offline dictionary metadata. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MetadataItems { + /// no description provided + pub encrypted_key: String, + /// no description provided + pub version: String, + /// no description provided + pub download_url: String, + /// no description provided + pub language: String, + /// no description provided + pub size: String, +} + +impl NestedType for MetadataItems {} +impl Part for MetadataItems {} + + +/// Author of this review. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReviewAuthor { + /// Name of this person. + #[serde(alias="displayName")] + pub display_name: String, +} + +impl NestedType for ReviewAuthor {} +impl Part for ReviewAuthor {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get bookshelves](struct.BookshelveGetCall.html) (response) +/// * [bookshelves get mylibrary](struct.MylibraryBookshelveGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Bookshelf { + /// Resource type for bookshelf metadata. + pub kind: String, + /// Description of this bookshelf. + pub description: String, + /// Title of this bookshelf. + pub title: String, + /// Number of volumes in this bookshelf. + #[serde(alias="volumeCount")] + pub volume_count: i32, + /// Created time for this bookshelf (formatted UTC timestamp with millisecond resolution). + pub created: String, + /// Last modified time of this bookshelf (formatted UTC timestamp with millisecond resolution). + pub updated: String, + /// Whether this bookshelf is PUBLIC or PRIVATE. + pub access: String, + /// Last time a volume was added or removed from this bookshelf (formatted UTC timestamp with millisecond resolution). + #[serde(alias="volumesLastUpdated")] + pub volumes_last_updated: String, + /// Id of this bookshelf, only unique by user. + pub id: i32, + /// URL to this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for Bookshelf {} + + +/// User settings in sub-objects, each for different purposes. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UsersettingsNotesExport { + /// no description provided + #[serde(alias="isEnabled")] + pub is_enabled: bool, + /// no description provided + #[serde(alias="folderName")] + pub folder_name: String, +} + +impl NestedType for UsersettingsNotesExport {} +impl Part for UsersettingsNotesExport {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [annotations insert mylibrary](struct.MylibraryAnnotationInsertCall.html) (request|response) +/// * [annotations update mylibrary](struct.MylibraryAnnotationUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Annotation { + /// Timestamp for the last time this annotation was modified. + pub updated: Option, + /// Indicates that this annotation is deleted. + pub deleted: Option, + /// Selection ranges for the most recent content version. + #[serde(alias="currentVersionRanges")] + pub current_version_ranges: Option, + /// Anchor text after excerpt. For requests, if the user bookmarked a screen that has no flowing text on it, then this field should be empty. + #[serde(alias="afterSelectedText")] + pub after_selected_text: Option, + /// The volume that this annotation belongs to. + #[serde(alias="volumeId")] + pub volume_id: Option, + /// Excerpt from the volume. + #[serde(alias="selectedText")] + pub selected_text: Option, + /// User-created data for this annotation. + pub data: Option, + /// Id of this annotation, in the form of a GUID. + pub id: Option, + /// Resource type. + pub kind: Option, + /// Timestamp for the created time of this annotation. + pub created: Option, + /// Anchor text before excerpt. For requests, if the user bookmarked a screen that has no flowing text on it, then this field should be empty. + #[serde(alias="beforeSelectedText")] + pub before_selected_text: Option, + /// Selection ranges sent from the client. + #[serde(alias="clientVersionRanges")] + pub client_version_ranges: Option, + /// Pages that this annotation spans. + #[serde(alias="pageIds")] + pub page_ids: Option>, + /// The layer this annotation is for. + #[serde(alias="layerId")] + pub layer_id: Option, + /// The highlight style for this annotation. + #[serde(alias="highlightStyle")] + pub highlight_style: Option, + /// no description provided + #[serde(alias="layerSummary")] + pub layer_summary: Option, + /// URL to this resource. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Annotation {} +impl ResponseResult for Annotation {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Review { + /// Star rating for this review. Possible values are ONE, TWO, THREE, FOUR, FIVE or NOT_RATED. + pub rating: String, + /// Resource type for a review. + pub kind: String, + /// Title for this review. + pub title: String, + /// Author of this review. + pub author: ReviewAuthor, + /// Volume that this review is for. + #[serde(alias="volumeId")] + pub volume_id: String, + /// Review text. + pub content: String, + /// Information regarding the source of this review, when the review is not from a Google Books user. + pub source: ReviewSource, + /// Date of this review. + pub date: String, + /// Source type for this review. Possible values are EDITORIAL, WEB_USER or GOOGLE_USER. + #[serde(alias="type")] + pub type_: String, + /// URL for the full review text, for reviews gathered from the web. + #[serde(alias="fullTextUrl")] + pub full_text_url: String, +} + +impl Part for Review {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DownloadAccessRestriction { + /// Client nonce for verification. Download access and client-validation only. + pub nonce: String, + /// Resource type. + pub kind: String, + /// If deviceAllowed, whether access was just acquired with this request. + #[serde(alias="justAcquired")] + pub just_acquired: bool, + /// If restricted, the maximum number of content download licenses for this volume. + #[serde(alias="maxDownloadDevices")] + pub max_download_devices: i32, + /// If restricted, the number of content download licenses already acquired (including the requesting client, if licensed). + #[serde(alias="downloadsAcquired")] + pub downloads_acquired: i32, + /// Identifies the volume for which this entry applies. + #[serde(alias="volumeId")] + pub volume_id: String, + /// If restricted, whether access is granted for this (user, device, volume). + #[serde(alias="deviceAllowed")] + pub device_allowed: bool, + /// Client app identifier for verification. Download access and client-validation only. + pub source: String, + /// Response signature. + pub signature: String, + /// Error/warning reason code. Additional codes may be added in the future. 0 OK 100 ACCESS_DENIED_PUBLISHER_LIMIT 101 ACCESS_DENIED_LIMIT 200 WARNING_USED_LAST_ACCESS + #[serde(alias="reasonCode")] + pub reason_code: String, + /// Error/warning message. + pub message: String, + /// Whether this volume has any download access restrictions. + pub restricted: bool, +} + +impl Part for DownloadAccessRestriction {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [release download access myconfig](struct.MyconfigReleaseDownloadAccesCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DownloadAccesses { + /// A list of download access responses. + #[serde(alias="downloadAccessList")] + pub download_access_list: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for DownloadAccesses {} + + +/// Information regarding the source of this review, when the review is not from a Google Books user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReviewSource { + /// Extra text about the source of the review. + #[serde(alias="extraDescription")] + pub extra_description: String, + /// URL of the source of the review. + pub url: String, + /// Name of the source. + pub description: String, +} + +impl NestedType for ReviewSource {} +impl Part for ReviewSource {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [readingpositions get mylibrary](struct.MylibraryReadingpositionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReadingPosition { + /// Position in a PDF file. + #[serde(alias="pdfPosition")] + pub pdf_position: String, + /// Resource type for a reading position. + pub kind: String, + /// Position in a volume for image-based content. + #[serde(alias="gbImagePosition")] + pub gb_image_position: String, + /// Position in a volume for text-based content. + #[serde(alias="gbTextPosition")] + pub gb_text_position: String, + /// Position in an EPUB as a CFI. + #[serde(alias="epubCfiPosition")] + pub epub_cfi_position: String, + /// Timestamp when this reading position was last updated (formatted UTC timestamp with millisecond resolution). + pub updated: String, + /// Volume id associated with this reading position. + #[serde(alias="volumeId")] + pub volume_id: String, +} + +impl ResponseResult for ReadingPosition {} + + +/// Offer retail (=discounted) price in Micros +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoOffersRetailPrice { + /// no description provided + #[serde(alias="currencyCode")] + pub currency_code: String, + /// no description provided + #[serde(alias="amountInMicros")] + pub amount_in_micros: f64, +} + +impl NestedType for VolumeSaleInfoOffersRetailPrice {} +impl Part for VolumeSaleInfoOffersRetailPrice {} + + +/// Search result information related to this volume. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSearchInfo { + /// A text snippet containing the search query. + #[serde(alias="textSnippet")] + pub text_snippet: String, +} + +impl NestedType for VolumeSearchInfo {} +impl Part for VolumeSearchInfo {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AnnotationsSummaryLayers { + /// no description provided + #[serde(alias="limitType")] + pub limit_type: String, + /// no description provided + #[serde(alias="remainingCharacterCount")] + pub remaining_character_count: i32, + /// no description provided + pub updated: String, + /// no description provided + #[serde(alias="allowedCharacterCount")] + pub allowed_character_count: i32, + /// no description provided + #[serde(alias="layerId")] + pub layer_id: String, +} + +impl NestedType for AnnotationsSummaryLayers {} +impl Part for AnnotationsSummaryLayers {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [annotation data get layers](struct.LayerAnnotationDataGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Annotationdata { + /// The type of annotation this data is for. + #[serde(alias="annotationType")] + pub annotation_type: String, + /// Resource Type + pub kind: String, + /// Timestamp for the last time this data was updated. (RFC 3339 UTC date-time format). + pub updated: String, + /// The volume id for this data. * + #[serde(alias="volumeId")] + pub volume_id: String, + /// Base64 encoded data for this annotation data. + pub encoded_data: String, + /// The Layer id for this data. * + #[serde(alias="layerId")] + pub layer_id: String, + /// no description provided + pub data: String, + /// Unique id for this annotation data. + pub id: String, + /// URL for this resource. * + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for Annotationdata {} + + +/// A list of image links for all the sizes that are available. (In LITE projection.) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeVolumeInfoImageLinks { + /// Image link for large size (width of ~800 pixels). (In LITE projection) + pub large: String, + /// Image link for extra large size (width of ~1280 pixels). (In LITE projection) + #[serde(alias="extraLarge")] + pub extra_large: String, + /// Image link for medium size (width of ~575 pixels). (In LITE projection) + pub medium: String, + /// Image link for small thumbnail size (width of ~80 pixels). (In LITE projection) + #[serde(alias="smallThumbnail")] + pub small_thumbnail: String, + /// Image link for small size (width of ~300 pixels). (In LITE projection) + pub small: String, + /// Image link for thumbnail size (width of ~128 pixels). (In LITE projection) + pub thumbnail: String, +} + +impl NestedType for VolumeVolumeInfoImageLinks {} +impl Part for VolumeVolumeInfoImageLinks {} + + +/// The actual selling price of the book. This is the same as the suggested retail or list price unless there are offers or discounts on this volume. (In LITE projection.) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoRetailPrice { + /// Amount in the currency listed below. (In LITE projection.) + pub amount: f64, + /// An ISO 4217, three-letter currency code. (In LITE projection.) + #[serde(alias="currencyCode")] + pub currency_code: String, +} + +impl NestedType for VolumeSaleInfoRetailPrice {} +impl Part for VolumeSaleInfoRetailPrice {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get layers](struct.LayerGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Layersummary { + /// Resource Type + pub kind: String, + /// The number of annotations for this layer. + #[serde(alias="annotationCount")] + pub annotation_count: i32, + /// The number of data items for this layer. + #[serde(alias="dataCount")] + pub data_count: i32, + /// The list of annotation types contained for this layer. + #[serde(alias="annotationTypes")] + pub annotation_types: Vec, + /// Timestamp for the last time an item in this layer was updated. (RFC 3339 UTC date-time format). + pub updated: String, + /// The volume id this resource is for. + #[serde(alias="volumeId")] + pub volume_id: String, + /// Link to get data for this annotation. + #[serde(alias="annotationsDataLink")] + pub annotations_data_link: String, + /// The link to get the annotations for this layer. + #[serde(alias="annotationsLink")] + pub annotations_link: String, + /// The content version this resource is for. + #[serde(alias="contentVersion")] + pub content_version: String, + /// The layer id for this summary. + #[serde(alias="layerId")] + pub layer_id: String, + /// The current version of this layer's volume annotations. Note that this version applies only to the data in the books.layers.volumeAnnotations.* responses. The actual annotation data is versioned separately. + #[serde(alias="volumeAnnotationsVersion")] + pub volume_annotations_version: String, + /// Unique id of this layer summary. + pub id: String, + /// URL to this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for Layersummary {} + + +/// Offer list (=undiscounted) price in Micros. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoOffersListPrice { + /// no description provided + #[serde(alias="currencyCode")] + pub currency_code: String, + /// no description provided + #[serde(alias="amountInMicros")] + pub amount_in_micros: f64, +} + +impl NestedType for VolumeSaleInfoOffersListPrice {} +impl Part for VolumeSaleInfoOffersListPrice {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [volume annotations get layers](struct.LayerVolumeAnnotationGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Volumeannotation { + /// The type of annotation this is. + #[serde(alias="annotationType")] + pub annotation_type: String, + /// Resource Type + pub kind: String, + /// Indicates that this annotation is deleted. + pub deleted: bool, + /// The content ranges to identify the selected text. + #[serde(alias="contentRanges")] + pub content_ranges: VolumeannotationContentRanges, + /// Timestamp for the last time this anntoation was updated. (RFC 3339 UTC date-time format). + pub updated: String, + /// The Volume this annotation is for. + #[serde(alias="volumeId")] + pub volume_id: String, + /// The annotation data id for this volume annotation. + #[serde(alias="annotationDataId")] + pub annotation_data_id: String, + /// Link to get data for this annotation. + #[serde(alias="annotationDataLink")] + pub annotation_data_link: String, + /// Pages the annotation spans. + #[serde(alias="pageIds")] + pub page_ids: Vec, + /// The Layer this annotation is for. + #[serde(alias="layerId")] + pub layer_id: String, + /// Excerpt from the volume. + #[serde(alias="selectedText")] + pub selected_text: String, + /// Data for this annotation. + pub data: String, + /// Unique id of this volume annotation. + pub id: String, + /// URL to this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for Volumeannotation {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [volume annotations list layers](struct.LayerVolumeAnnotationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Volumeannotations { + /// Token to pass in for pagination for the next page. This will not be present if this request does not have more results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of volume annotations. + pub items: Vec, + /// Resource type + pub kind: String, + /// The version string for all of the volume annotations in this layer (not just the ones in this response). Note: the version string doesn't apply to the annotation data, just the information in this response (e.g. the location of annotations in the book). + pub version: String, + /// The total number of volume annotations found. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for Volumeannotations {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [annotation data list layers](struct.LayerAnnotationDataListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Annotationsdata { + /// Token to pass in for pagination for the next page. This will not be present if this request does not have more results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of Annotation Data. + pub items: Vec, + /// Resource type + pub kind: String, + /// The total number of volume annotations found. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for Annotationsdata {} + + +/// Industry standard identifiers for this volume. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeVolumeInfoIndustryIdentifiers { + /// Industry specific volume identifier. + pub identifier: String, + /// Identifier type. Possible values are ISBN_10, ISBN_13, ISSN and OTHER. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for VolumeVolumeInfoIndustryIdentifiers {} +impl Part for VolumeVolumeInfoIndustryIdentifiers {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AnnotationLayerSummary { + /// Type of limitation on this layer. "limited" or "unlimited" for the "copy" layer. + #[serde(alias="limitType")] + pub limit_type: String, + /// Remaining allowed characters on this layer, especially for the "copy" layer. + #[serde(alias="remainingCharacterCount")] + pub remaining_character_count: i32, + /// Maximum allowed characters on this layer, especially for the "copy" layer. + #[serde(alias="allowedCharacterCount")] + pub allowed_character_count: i32, +} + +impl NestedType for AnnotationLayerSummary {} +impl Part for AnnotationLayerSummary {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get promooffer](struct.PromoofferGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Offers { + /// A list of offers. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Offers {} + + +/// Information about epub content. (In LITE projection.) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeAccessInfoEpub { + /// Is a flowing text epub available either as public domain or for purchase. (In LITE projection.) + #[serde(alias="isAvailable")] + pub is_available: bool, + /// URL to download epub. (In LITE projection.) + #[serde(alias="downloadLink")] + pub download_link: String, + /// URL to retrieve ACS token for epub download. (In LITE projection.) + #[serde(alias="acsTokenLink")] + pub acs_token_link: String, +} + +impl NestedType for VolumeAccessInfoEpub {} +impl Part for VolumeAccessInfoEpub {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list category volumes onboarding](struct.OnboardingListCategoryVolumeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Volume2 { + /// no description provided + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of volumes. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Volume2 {} + + +/// Information about pdf content. (In LITE projection.) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeAccessInfoPdf { + /// Is a scanned image pdf available either as public domain or for purchase. (In LITE projection.) + #[serde(alias="isAvailable")] + pub is_available: bool, + /// URL to download pdf. (In LITE projection.) + #[serde(alias="downloadLink")] + pub download_link: String, + /// URL to retrieve ACS token for pdf download. (In LITE projection.) + #[serde(alias="acsTokenLink")] + pub acs_token_link: String, +} + +impl NestedType for VolumeAccessInfoPdf {} +impl Part for VolumeAccessInfoPdf {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [annotations summary mylibrary](struct.MylibraryAnnotationSummaryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AnnotationsSummary { + /// no description provided + pub layers: Vec, + /// no description provided + pub kind: String, +} + +impl ResponseResult for AnnotationsSummary {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [bookshelves list mylibrary](struct.MylibraryBookshelveListCall.html) (response) +/// * [list bookshelves](struct.BookshelveListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Bookshelves { + /// A list of bookshelves. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Bookshelves {} + + +/// A layer should appear here if and only if the layer exists for this book. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeLayerInfoLayers { + /// The current version of this layer's volume annotations. Note that this version applies only to the data in the books.layers.volumeAnnotations.* responses. The actual annotation data is versioned separately. + #[serde(alias="volumeAnnotationsVersion")] + pub volume_annotations_version: String, + /// The layer id of this layer (e.g. "geo"). + #[serde(alias="layerId")] + pub layer_id: String, +} + +impl NestedType for VolumeLayerInfoLayers {} +impl Part for VolumeLayerInfoLayers {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list layers](struct.LayerListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Layersummaries { + /// The total number of layer summaries found. + #[serde(alias="totalItems")] + pub total_items: i32, + /// A list of layer summary items. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Layersummaries {} + + +/// A list of offers. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OffersItems { + /// no description provided + #[serde(alias="gservicesKey")] + pub gservices_key: String, + /// no description provided + pub items: Vec, + /// no description provided + #[serde(alias="artUrl")] + pub art_url: String, + /// no description provided + pub id: String, +} + +impl NestedType for OffersItems {} +impl Part for OffersItems {} + + +/// Copy/Paste accounting information. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeUserInfoCopy { + /// no description provided + #[serde(alias="limitType")] + pub limit_type: String, + /// no description provided + #[serde(alias="remainingCharacterCount")] + pub remaining_character_count: i32, + /// no description provided + pub updated: String, + /// no description provided + #[serde(alias="allowedCharacterCount")] + pub allowed_character_count: i32, +} + +impl NestedType for VolumeUserInfoCopy {} +impl Part for VolumeUserInfoCopy {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [recommended rate volumes](struct.VolumeRecommendedRateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BooksVolumesRecommendedRateResponse { + /// no description provided + pub consistency_token: String, +} + +impl ResponseResult for BooksVolumesRecommendedRateResponse {} + + +/// User specific information related to this volume. (e.g. page this user last read or whether they purchased this book) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeUserInfo { + /// Whether or not this volume is currently in "my books." + #[serde(alias="isInMyBooks")] + pub is_in_my_books: bool, + /// Period during this book is/was a valid rental. + #[serde(alias="rentalPeriod")] + pub rental_period: VolumeUserInfoRentalPeriod, + /// Timestamp when this volume was last modified by a user action, such as a reading position update, volume purchase or writing a review. (RFC 3339 UTC date-time format). + pub updated: String, + /// no description provided + #[serde(alias="userUploadedVolumeInfo")] + pub user_uploaded_volume_info: VolumeUserInfoUserUploadedVolumeInfo, + /// Whether this book is an active or an expired rental. + #[serde(alias="rentalState")] + pub rental_state: String, + /// Whether or not this volume was purchased by the authenticated user making the request. (In LITE projection.) + #[serde(alias="isPurchased")] + pub is_purchased: bool, + /// The user's current reading position in the volume, if one is available. (In LITE projection.) + #[serde(alias="readingPosition")] + pub reading_position: ReadingPosition, + /// Whether or not this volume was pre-ordered by the authenticated user making the request. (In LITE projection.) + #[serde(alias="isPreordered")] + pub is_preordered: bool, + /// Copy/Paste accounting information. + pub copy: VolumeUserInfoCopy, + /// This user's review of this volume, if one exists. + pub review: Review, + /// Whether or not this volume was user uploaded. + #[serde(alias="isUploaded")] + pub is_uploaded: bool, +} + +impl NestedType for VolumeUserInfo {} +impl Part for VolumeUserInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update book cloudloading](struct.CloudloadingUpdateBookCall.html) (request|response) +/// * [add book cloudloading](struct.CloudloadingAddBookCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BooksCloudloadingResource { + /// no description provided + pub author: Option, + /// no description provided + #[serde(alias="processingState")] + pub processing_state: Option, + /// no description provided + #[serde(alias="volumeId")] + pub volume_id: Option, + /// no description provided + pub title: Option, +} + +impl RequestValue for BooksCloudloadingResource {} +impl ResponseResult for BooksCloudloadingResource {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeUserInfoUserUploadedVolumeInfo { + /// no description provided + #[serde(alias="processingState")] + pub processing_state: String, +} + +impl NestedType for VolumeUserInfoUserUploadedVolumeInfo {} +impl Part for VolumeUserInfoUserUploadedVolumeInfo {} + + +/// Suggested retail price. (In LITE projection.) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoListPrice { + /// Amount in the currency listed below. (In LITE projection.) + pub amount: f64, + /// An ISO 4217, three-letter currency code. (In LITE projection.) + #[serde(alias="currencyCode")] + pub currency_code: String, +} + +impl NestedType for VolumeSaleInfoListPrice {} +impl Part for VolumeSaleInfoListPrice {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BooksAnnotationsRange { + /// The starting position for the range. + #[serde(alias="startPosition")] + pub start_position: String, + /// The ending position for the range. + #[serde(alias="endPosition")] + pub end_position: String, + /// The offset from the starting position. + #[serde(alias="startOffset")] + pub start_offset: String, + /// The offset from the ending position. + #[serde(alias="endOffset")] + pub end_offset: String, +} + +impl Part for BooksAnnotationsRange {} + + +/// Any information about a volume related to reading or obtaining that volume text. This information can depend on country (books may be public domain in one country but not in another, e.g.). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeAccessInfo { + /// URL to read this volume on the Google Books site. Link will not allow users to read non-viewable volumes. + #[serde(alias="webReaderLink")] + pub web_reader_link: String, + /// Whether or not this book is public domain in the country listed above. + #[serde(alias="publicDomain")] + pub public_domain: bool, + /// Whether this volume requires that the client explicitly request offline download license rather than have it done automatically when loading the content, if the client supports it. + #[serde(alias="explicitOfflineLicenseManagement")] + pub explicit_offline_license_management: bool, + /// Whether this volume can be embedded in a viewport using the Embedded Viewer API. + pub embeddable: bool, + /// Information about a volume's download license access restrictions. + #[serde(alias="downloadAccess")] + pub download_access: DownloadAccessRestriction, + /// The two-letter ISO_3166-1 country code for which this access information is valid. (In LITE projection.) + pub country: String, + /// For ordered but not yet processed orders, we give a URL that can be used to go to the appropriate Google Wallet page. + #[serde(alias="viewOrderUrl")] + pub view_order_url: String, + /// Whether text-to-speech is permitted for this volume. Values can be ALLOWED, ALLOWED_FOR_ACCESSIBILITY, or NOT_ALLOWED. + #[serde(alias="textToSpeechPermission")] + pub text_to_speech_permission: String, + /// URL to the Google Drive viewer if this volume is uploaded by the user by selecting the file from Google Drive. + #[serde(alias="driveImportedContentLink")] + pub drive_imported_content_link: String, + /// Information about pdf content. (In LITE projection.) + pub pdf: VolumeAccessInfoPdf, + /// Whether quote sharing is allowed for this volume. + #[serde(alias="quoteSharingAllowed")] + pub quote_sharing_allowed: bool, + /// The read access of a volume. Possible values are PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN. This value depends on the country listed above. A value of PARTIAL means that the publisher has allowed some portion of the volume to be viewed publicly, without purchase. This can apply to eBooks as well as non-eBooks. Public domain books will always have a value of ALL_PAGES. + pub viewability: String, + /// Information about epub content. (In LITE projection.) + pub epub: VolumeAccessInfoEpub, + /// Combines the access and viewability of this volume into a single status field for this user. Values can be FULL_PURCHASED, FULL_PUBLIC_DOMAIN, SAMPLE or NONE. (In LITE projection.) + #[serde(alias="accessViewStatus")] + pub access_view_status: String, +} + +impl NestedType for VolumeAccessInfo {} +impl Part for VolumeAccessInfo {} + + +/// Selection ranges for the most recent content version. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AnnotationCurrentVersionRanges { + /// Range in image CFI format for this annotation for version above. + #[serde(alias="imageCfiRange")] + pub image_cfi_range: BooksAnnotationsRange, + /// Range in GB text format for this annotation for version above. + #[serde(alias="gbTextRange")] + pub gb_text_range: BooksAnnotationsRange, + /// Content version applicable to ranges below. + #[serde(alias="contentVersion")] + pub content_version: String, + /// Range in CFI format for this annotation for version above. + #[serde(alias="cfiRange")] + pub cfi_range: BooksAnnotationsRange, + /// Range in GB image format for this annotation for version above. + #[serde(alias="gbImageRange")] + pub gb_image_range: BooksAnnotationsRange, +} + +impl NestedType for AnnotationCurrentVersionRanges {} +impl Part for AnnotationCurrentVersionRanges {} + + +/// Any information about a volume related to the eBookstore and/or purchaseability. This information can depend on the country where the request originates from (i.e. books may not be for sale in certain countries). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfo { + /// The two-letter ISO_3166-1 country code for which this sale information is valid. (In LITE projection.) + pub country: String, + /// The actual selling price of the book. This is the same as the suggested retail or list price unless there are offers or discounts on this volume. (In LITE projection.) + #[serde(alias="retailPrice")] + pub retail_price: VolumeSaleInfoRetailPrice, + /// Whether or not this volume is an eBook (can be added to the My eBooks shelf). + #[serde(alias="isEbook")] + pub is_ebook: bool, + /// Offers available for this volume (sales and rentals). + pub offers: Vec, + /// Whether or not this book is available for sale or offered for free in the Google eBookstore for the country listed above. Possible values are FOR_SALE, FOR_RENTAL_ONLY, FOR_SALE_AND_RENTAL, FREE, NOT_FOR_SALE, or FOR_PREORDER. + pub saleability: String, + /// URL to purchase this volume on the Google Books site. (In LITE projection) + #[serde(alias="buyLink")] + pub buy_link: String, + /// The date on which this book is available for sale. + #[serde(alias="onSaleDate")] + pub on_sale_date: String, + /// Suggested retail price. (In LITE projection.) + #[serde(alias="listPrice")] + pub list_price: VolumeSaleInfoListPrice, +} + +impl NestedType for VolumeSaleInfo {} +impl Part for VolumeSaleInfo {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [useruploaded list volumes](struct.VolumeUseruploadedListCall.html) (response) +/// * [sync volume licenses myconfig](struct.MyconfigSyncVolumeLicenseCall.html) (response) +/// * [list volumes](struct.VolumeListCall.html) (response) +/// * [associated list volumes](struct.VolumeAssociatedListCall.html) (response) +/// * [volumes list bookshelves](struct.BookshelveVolumeListCall.html) (response) +/// * [recommended list volumes](struct.VolumeRecommendedListCall.html) (response) +/// * [bookshelves volumes list mylibrary](struct.MylibraryBookshelveVolumeListCall.html) (response) +/// * [mybooks list volumes](struct.VolumeMybookListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Volumes { + /// Total number of volumes found. This might be greater than the number of volumes returned in this response if results have been paginated. + #[serde(alias="totalItems")] + pub total_items: i32, + /// A list of volumes. + pub items: Vec, + /// Resource type. + pub kind: String, +} + +impl ResponseResult for Volumes {} + + +/// Period during this book is/was a valid rental. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeUserInfoRentalPeriod { + /// no description provided + #[serde(alias="startUtcSec")] + pub start_utc_sec: String, + /// no description provided + #[serde(alias="endUtcSec")] + pub end_utc_sec: String, +} + +impl NestedType for VolumeUserInfoRentalPeriod {} +impl Part for VolumeUserInfoRentalPeriod {} + + +/// The content ranges to identify the selected text. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeannotationContentRanges { + /// Range in GB image format for this annotation for version above. + #[serde(alias="gbImageRange")] + pub gb_image_range: BooksAnnotationsRange, + /// Range in GB text format for this annotation for version above. + #[serde(alias="gbTextRange")] + pub gb_text_range: BooksAnnotationsRange, + /// Content version applicable to ranges below. + #[serde(alias="contentVersion")] + pub content_version: String, + /// Range in CFI format for this annotation for version above. + #[serde(alias="cfiRange")] + pub cfi_range: BooksAnnotationsRange, +} + +impl NestedType for VolumeannotationContentRanges {} +impl Part for VolumeannotationContentRanges {} + + +/// The rental duration (for rental offers only). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct VolumeSaleInfoOffersRentalDuration { + /// no description provided + pub count: f64, + /// no description provided + pub unit: String, +} + +impl NestedType for VolumeSaleInfoOffersRentalDuration {} +impl Part for VolumeSaleInfoOffersRentalDuration {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *layer* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `annotation_data_get(...)`, `annotation_data_list(...)`, `get(...)`, `list(...)`, `volume_annotations_get(...)` and `volume_annotations_list(...)` +/// // to build up your call. +/// let rb = hub.layers(); +/// # } +/// ``` +pub struct LayerMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for LayerMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the annotation data. + pub fn annotation_data_get(&self, volume_id: &str, layer_id: &str, annotation_data_id: &str, content_version: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + LayerAnnotationDataGetCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _layer_id: layer_id.to_string(), + _annotation_data_id: annotation_data_id.to_string(), + _content_version: content_version.to_string(), + _w: Default::default(), + _source: Default::default(), + _scale: Default::default(), + _locale: Default::default(), + _h: Default::default(), + _allow_web_definitions: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the volume annotation. + pub fn volume_annotations_get(&self, volume_id: &str, layer_id: &str, annotation_id: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + LayerVolumeAnnotationGetCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _layer_id: layer_id.to_string(), + _annotation_id: annotation_id.to_string(), + _source: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the layer summaries for a volume. + pub fn list(&self, volume_id: &str) -> LayerListCall<'a, C, NC, A> { + LayerListCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _source: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _content_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the layer summary for a volume. + pub fn get(&self, volume_id: &str, summary_id: &str) -> LayerGetCall<'a, C, NC, A> { + LayerGetCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _summary_id: summary_id.to_string(), + _source: Default::default(), + _content_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the volume annotations for a volume and layer. + pub fn volume_annotations_list(&self, volume_id: &str, layer_id: &str, content_version: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + LayerVolumeAnnotationListCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _layer_id: layer_id.to_string(), + _content_version: content_version.to_string(), + _volume_annotations_version: Default::default(), + _updated_min: Default::default(), + _updated_max: Default::default(), + _start_position: Default::default(), + _start_offset: Default::default(), + _source: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _end_position: Default::default(), + _end_offset: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the annotation data for a volume and layer. + pub fn annotation_data_list(&self, volume_id: &str, layer_id: &str, content_version: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + LayerAnnotationDataListCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _layer_id: layer_id.to_string(), + _content_version: content_version.to_string(), + _w: Default::default(), + _updated_min: Default::default(), + _updated_max: Default::default(), + _source: Default::default(), + _scale: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _h: Default::default(), + _annotation_data_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *volume* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `associated_list(...)`, `get(...)`, `list(...)`, `mybooks_list(...)`, `recommended_list(...)`, `recommended_rate(...)` and `useruploaded_list(...)` +/// // to build up your call. +/// let rb = hub.volumes(); +/// # } +/// ``` +pub struct VolumeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for VolumeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Rate a recommended book for the current user. + pub fn recommended_rate(&self, rating: &str, volume_id: &str) -> VolumeRecommendedRateCall<'a, C, NC, A> { + VolumeRecommendedRateCall { + hub: self.hub, + _rating: rating.to_string(), + _volume_id: volume_id.to_string(), + _source: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Return a list of books in My Library. + pub fn mybooks_list(&self) -> VolumeMybookListCall<'a, C, NC, A> { + VolumeMybookListCall { + hub: self.hub, + _start_index: Default::default(), + _source: Default::default(), + _processing_state: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _acquire_method: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Performs a book search. + pub fn list(&self, q: &str) -> VolumeListCall<'a, C, NC, A> { + VolumeListCall { + hub: self.hub, + _q: q.to_string(), + _start_index: Default::default(), + _source: Default::default(), + _show_preorders: Default::default(), + _projection: Default::default(), + _print_type: Default::default(), + _partner: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _library_restrict: Default::default(), + _lang_restrict: Default::default(), + _filter: Default::default(), + _download: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Return a list of books uploaded by the current user. + pub fn useruploaded_list(&self) -> VolumeUseruploadedListCall<'a, C, NC, A> { + VolumeUseruploadedListCall { + hub: self.hub, + _volume_id: Default::default(), + _start_index: Default::default(), + _source: Default::default(), + _processing_state: Default::default(), + _max_results: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Return a list of associated books. + pub fn associated_list(&self, volume_id: &str) -> VolumeAssociatedListCall<'a, C, NC, A> { + VolumeAssociatedListCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _source: Default::default(), + _locale: Default::default(), + _association: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets volume information for a single volume. + pub fn get(&self, volume_id: &str) -> VolumeGetCall<'a, C, NC, A> { + VolumeGetCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _user_library_consistent_read: Default::default(), + _source: Default::default(), + _projection: Default::default(), + _partner: Default::default(), + _country: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Return a list of recommended books for the current user. + pub fn recommended_list(&self) -> VolumeRecommendedListCall<'a, C, NC, A> { + VolumeRecommendedListCall { + hub: self.hub, + _source: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *dictionary* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list_offline_metadata(...)` +/// // to build up your call. +/// let rb = hub.dictionary(); +/// # } +/// ``` +pub struct DictionaryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DictionaryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DictionaryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of offline dictionary meatadata available + pub fn list_offline_metadata(&self, cpksver: &str) -> DictionaryListOfflineMetadataCall<'a, C, NC, A> { + DictionaryListOfflineMetadataCall { + hub: self.hub, + _cpksver: cpksver.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *bookshelve* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)` and `volumes_list(...)` +/// // to build up your call. +/// let rb = hub.bookshelves(); +/// # } +/// ``` +pub struct BookshelveMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BookshelveMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BookshelveMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves volumes in a specific bookshelf for the specified user. + pub fn volumes_list(&self, user_id: &str, shelf: &str) -> BookshelveVolumeListCall<'a, C, NC, A> { + BookshelveVolumeListCall { + hub: self.hub, + _user_id: user_id.to_string(), + _shelf: shelf.to_string(), + _start_index: Default::default(), + _source: Default::default(), + _show_preorders: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of public bookshelves for the specified user. + pub fn list(&self, user_id: &str) -> BookshelveListCall<'a, C, NC, A> { + BookshelveListCall { + hub: self.hub, + _user_id: user_id.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves metadata for a specific bookshelf for the specified user. + pub fn get(&self, user_id: &str, shelf: &str) -> BookshelveGetCall<'a, C, NC, A> { + BookshelveGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _shelf: shelf.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *promooffer* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `accept(...)`, `dismiss(...)` and `get(...)` +/// // to build up your call. +/// let rb = hub.promooffer(); +/// # } +/// ``` +pub struct PromoofferMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PromoofferMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PromoofferMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// + pub fn accept(&self) -> PromoofferAcceptCall<'a, C, NC, A> { + PromoofferAcceptCall { + hub: self.hub, + _volume_id: Default::default(), + _serial: Default::default(), + _product: Default::default(), + _offer_id: Default::default(), + _model: Default::default(), + _manufacturer: Default::default(), + _device: Default::default(), + _android_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// + pub fn dismiss(&self) -> PromoofferDismisCall<'a, C, NC, A> { + PromoofferDismisCall { + hub: self.hub, + _serial: Default::default(), + _product: Default::default(), + _offer_id: Default::default(), + _model: Default::default(), + _manufacturer: Default::default(), + _device: Default::default(), + _android_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of promo offers available to the user + pub fn get(&self) -> PromoofferGetCall<'a, C, NC, A> { + PromoofferGetCall { + hub: self.hub, + _serial: Default::default(), + _product: Default::default(), + _model: Default::default(), + _manufacturer: Default::default(), + _device: Default::default(), + _android_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *onboarding* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list_categories(...)` and `list_category_volumes(...)` +/// // to build up your call. +/// let rb = hub.onboarding(); +/// # } +/// ``` +pub struct OnboardingMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for OnboardingMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> OnboardingMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List categories for onboarding experience. + pub fn list_categories(&self) -> OnboardingListCategoryCall<'a, C, NC, A> { + OnboardingListCategoryCall { + hub: self.hub, + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List available volumes under categories for onboarding experience. + pub fn list_category_volumes(&self) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + OnboardingListCategoryVolumeCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: Default::default(), + _locale: Default::default(), + _category_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *myconfig* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get_user_settings(...)`, `release_download_access(...)`, `request_access(...)`, `sync_volume_licenses(...)` and `update_user_settings(...)` +/// // to build up your call. +/// let rb = hub.myconfig(); +/// # } +/// ``` +pub struct MyconfigMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MyconfigMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Request concurrent and download access restrictions. + pub fn request_access(&self, source: &str, volume_id: &str, nonce: &str, cpksver: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + MyconfigRequestAccesCall { + hub: self.hub, + _source: source.to_string(), + _volume_id: volume_id.to_string(), + _nonce: nonce.to_string(), + _cpksver: cpksver.to_string(), + _locale: Default::default(), + _license_types: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Release downloaded content access restriction. + pub fn release_download_access(&self, volume_ids: &Vec, cpksver: &str) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + MyconfigReleaseDownloadAccesCall { + hub: self.hub, + _volume_ids: volume_ids.clone(), + _cpksver: cpksver.to_string(), + _source: Default::default(), + _locale: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Request downloaded content access for specified volumes on the My eBooks shelf. + pub fn sync_volume_licenses(&self, source: &str, nonce: &str, cpksver: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + MyconfigSyncVolumeLicenseCall { + hub: self.hub, + _source: source.to_string(), + _nonce: nonce.to_string(), + _cpksver: cpksver.to_string(), + _volume_ids: Default::default(), + _show_preorders: Default::default(), + _locale: Default::default(), + _features: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the current settings for the user. + pub fn get_user_settings(&self) -> MyconfigGetUserSettingCall<'a, C, NC, A> { + MyconfigGetUserSettingCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the settings for the user. Unspecified sub-objects will retain the existing value. + pub fn update_user_settings(&self, request: &Usersettings) -> MyconfigUpdateUserSettingCall<'a, C, NC, A> { + MyconfigUpdateUserSettingCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *mylibrary* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `annotations_delete(...)`, `annotations_insert(...)`, `annotations_list(...)`, `annotations_summary(...)`, `annotations_update(...)`, `bookshelves_add_volume(...)`, `bookshelves_clear_volumes(...)`, `bookshelves_get(...)`, `bookshelves_list(...)`, `bookshelves_move_volume(...)`, `bookshelves_remove_volume(...)`, `bookshelves_volumes_list(...)`, `readingpositions_get(...)` and `readingpositions_set_position(...)` +/// // to build up your call. +/// let rb = hub.mylibrary(); +/// # } +/// ``` +pub struct MylibraryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MylibraryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Clears all volumes from a bookshelf. + pub fn bookshelves_clear_volumes(&self, shelf: &str) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> { + MylibraryBookshelveClearVolumeCall { + hub: self.hub, + _shelf: shelf.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Moves a volume within a bookshelf. + pub fn bookshelves_move_volume(&self, shelf: &str, volume_id: &str, volume_position: i32) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + MylibraryBookshelveMoveVolumeCall { + hub: self.hub, + _shelf: shelf.to_string(), + _volume_id: volume_id.to_string(), + _volume_position: volume_position, + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets volume information for volumes on a bookshelf. + pub fn bookshelves_volumes_list(&self, shelf: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + MylibraryBookshelveVolumeListCall { + hub: self.hub, + _shelf: shelf.to_string(), + _start_index: Default::default(), + _source: Default::default(), + _show_preorders: Default::default(), + _q: Default::default(), + _projection: Default::default(), + _max_results: Default::default(), + _country: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the summary of specified layers. + pub fn annotations_summary(&self, layer_ids: &Vec, volume_id: &str) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> { + MylibraryAnnotationSummaryCall { + hub: self.hub, + _layer_ids: layer_ids.clone(), + _volume_id: volume_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an annotation. + pub fn annotations_delete(&self, annotation_id: &str) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> { + MylibraryAnnotationDeleteCall { + hub: self.hub, + _annotation_id: annotation_id.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a volume to a bookshelf. + pub fn bookshelves_add_volume(&self, shelf: &str, volume_id: &str) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + MylibraryBookshelveAddVolumeCall { + hub: self.hub, + _shelf: shelf.to_string(), + _volume_id: volume_id.to_string(), + _source: Default::default(), + _reason: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new annotation. + pub fn annotations_insert(&self, request: &Annotation) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + MylibraryAnnotationInsertCall { + hub: self.hub, + _request: request.clone(), + _source: Default::default(), + _show_only_summary_in_response: Default::default(), + _country: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a volume from a bookshelf. + pub fn bookshelves_remove_volume(&self, shelf: &str, volume_id: &str) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + MylibraryBookshelveRemoveVolumeCall { + hub: self.hub, + _shelf: shelf.to_string(), + _volume_id: volume_id.to_string(), + _source: Default::default(), + _reason: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of annotations, possibly filtered. + pub fn annotations_list(&self) -> MylibraryAnnotationListCall<'a, C, NC, A> { + MylibraryAnnotationListCall { + hub: self.hub, + _volume_id: Default::default(), + _updated_min: Default::default(), + _updated_max: Default::default(), + _source: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _layer_ids: Default::default(), + _layer_id: Default::default(), + _content_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing annotation. + pub fn annotations_update(&self, request: &Annotation, annotation_id: &str) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> { + MylibraryAnnotationUpdateCall { + hub: self.hub, + _request: request.clone(), + _annotation_id: annotation_id.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets my reading position information for a volume. + pub fn readingpositions_set_position(&self, volume_id: &str, timestamp: &str, position: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + MylibraryReadingpositionSetPositionCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _timestamp: timestamp.to_string(), + _position: position.to_string(), + _source: Default::default(), + _device_cookie: Default::default(), + _content_version: Default::default(), + _action: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves metadata for a specific bookshelf belonging to the authenticated user. + pub fn bookshelves_get(&self, shelf: &str) -> MylibraryBookshelveGetCall<'a, C, NC, A> { + MylibraryBookshelveGetCall { + hub: self.hub, + _shelf: shelf.to_string(), + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of bookshelves belonging to the authenticated user. + pub fn bookshelves_list(&self) -> MylibraryBookshelveListCall<'a, C, NC, A> { + MylibraryBookshelveListCall { + hub: self.hub, + _source: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves my reading position information for a volume. + pub fn readingpositions_get(&self, volume_id: &str) -> MylibraryReadingpositionGetCall<'a, C, NC, A> { + MylibraryReadingpositionGetCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _source: Default::default(), + _content_version: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *cloudloading* resources. +/// It is not used directly, but through the `Books` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-books1" as books1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use books1::Books; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Books::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `add_book(...)`, `delete_book(...)` and `update_book(...)` +/// // to build up your call. +/// let rb = hub.cloudloading(); +/// # } +/// ``` +pub struct CloudloadingMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CloudloadingMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CloudloadingMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// + pub fn add_book(&self) -> CloudloadingAddBookCall<'a, C, NC, A> { + CloudloadingAddBookCall { + hub: self.hub, + _upload_client_token: Default::default(), + _name: Default::default(), + _mime_type: Default::default(), + _drive_document_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// + pub fn update_book(&self, request: &BooksCloudloadingResource) -> CloudloadingUpdateBookCall<'a, C, NC, A> { + CloudloadingUpdateBookCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Remove the book and its contents + pub fn delete_book(&self, volume_id: &str) -> CloudloadingDeleteBookCall<'a, C, NC, A> { + CloudloadingDeleteBookCall { + hub: self.hub, + _volume_id: volume_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Gets the annotation data. +/// +/// A builder for the *annotationData.get* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().annotation_data_get("volumeId", "layerId", "annotationDataId", "contentVersion") +/// .w(-33) +/// .source("invidunt") +/// .scale(-82) +/// .locale("accusam") +/// .h(-56) +/// .allow_web_definitions(true) +/// .doit(); +/// # } +/// ``` +pub struct LayerAnnotationDataGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _layer_id: String, + _annotation_data_id: String, + _content_version: String, + _w: Option, + _source: Option, + _scale: Option, + _locale: Option, + _h: Option, + _allow_web_definitions: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerAnnotationDataGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerAnnotationDataGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Annotationdata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.annotationData.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("layerId", self._layer_id.to_string())); + params.push(("annotationDataId", self._annotation_data_id.to_string())); + params.push(("contentVersion", self._content_version.to_string())); + if let Some(value) = self._w { + params.push(("w", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._scale { + params.push(("scale", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if let Some(value) = self._h { + params.push(("h", value.to_string())); + } + if let Some(value) = self._allow_web_definitions { + params.push(("allowWebDefinitions", value.to_string())); + } + for &field in ["alt", "volumeId", "layerId", "annotationDataId", "contentVersion", "w", "source", "scale", "locale", "h", "allowWebDefinitions"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layers/{layerId}/data/{annotationDataId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId"), ("{layerId}", "layerId"), ("{annotationDataId}", "annotationDataId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["volumeId", "layerId", "annotationDataId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve annotations for. + pub fn volume_id(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *layer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the layer to get the annotations. + pub fn layer_id(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._layer_id = new_value.to_string(); + self + } + /// Sets the *annotation data id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the annotation data to retrieve. + pub fn annotation_data_id(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._annotation_data_id = new_value.to_string(); + self + } + /// Sets the *content version* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The content version for the volume you are trying to retrieve. + pub fn content_version(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._content_version = new_value.to_string(); + self + } + /// Sets the *w* query property to the given value. + /// + /// + /// The requested pixel width for any images. If width is provided height must also be provided. + pub fn w(mut self, new_value: i32) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._w = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *scale* query property to the given value. + /// + /// + /// The requested scale for the image. + pub fn scale(mut self, new_value: i32) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._scale = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale information for the data. ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. + pub fn locale(mut self, new_value: &str) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *h* query property to the given value. + /// + /// + /// The requested pixel height for any images. If height is provided width must also be provided. + pub fn h(mut self, new_value: i32) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._h = Some(new_value); + self + } + /// Sets the *allow web definitions* query property to the given value. + /// + /// + /// For the dictionary layer. Whether or not to allow web definitions. + pub fn allow_web_definitions(mut self, new_value: bool) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._allow_web_definitions = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerAnnotationDataGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerAnnotationDataGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerAnnotationDataGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the volume annotation. +/// +/// A builder for the *volumeAnnotations.get* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().volume_annotations_get("volumeId", "layerId", "annotationId") +/// .source("eirmod") +/// .locale("sanctus") +/// .doit(); +/// # } +/// ``` +pub struct LayerVolumeAnnotationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _layer_id: String, + _annotation_id: String, + _source: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerVolumeAnnotationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerVolumeAnnotationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumeannotation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.volumeAnnotations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("layerId", self._layer_id.to_string())); + params.push(("annotationId", self._annotation_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "volumeId", "layerId", "annotationId", "source", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layers/{layerId}/annotations/{annotationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId"), ("{layerId}", "layerId"), ("{annotationId}", "annotationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["volumeId", "layerId", "annotationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve annotations for. + pub fn volume_id(mut self, new_value: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *layer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the layer to get the annotations. + pub fn layer_id(mut self, new_value: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._layer_id = new_value.to_string(); + self + } + /// Sets the *annotation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the volume annotation to retrieve. + pub fn annotation_id(mut self, new_value: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._annotation_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale information for the data. ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. + pub fn locale(mut self, new_value: &str) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerVolumeAnnotationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the layer summaries for a volume. +/// +/// A builder for the *list* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().list("volumeId") +/// .source("amet") +/// .page_token("et") +/// .max_results(56) +/// .content_version("ut") +/// .doit(); +/// # } +/// ``` +pub struct LayerListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _source: Option, + _page_token: Option, + _max_results: Option, + _content_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Layersummaries)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._content_version { + params.push(("contentVersion", value.to_string())); + } + for &field in ["alt", "volumeId", "source", "pageToken", "maxResults", "contentVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layersummary".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["volumeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve layers for. + pub fn volume_id(mut self, new_value: &str) -> LayerListCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous page. + pub fn page_token(mut self, new_value: &str) -> LayerListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> LayerListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *content version* query property to the given value. + /// + /// + /// The content version for the requested volume. + pub fn content_version(mut self, new_value: &str) -> LayerListCall<'a, C, NC, A> { + self._content_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the layer summary for a volume. +/// +/// A builder for the *get* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().get("volumeId", "summaryId") +/// .source("dolor") +/// .content_version("dolor") +/// .doit(); +/// # } +/// ``` +pub struct LayerGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _summary_id: String, + _source: Option, + _content_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Layersummary)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("summaryId", self._summary_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._content_version { + params.push(("contentVersion", value.to_string())); + } + for &field in ["alt", "volumeId", "summaryId", "source", "contentVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layersummary/{summaryId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId"), ("{summaryId}", "summaryId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["volumeId", "summaryId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve layers for. + pub fn volume_id(mut self, new_value: &str) -> LayerGetCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *summary id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the layer to get the summary for. + pub fn summary_id(mut self, new_value: &str) -> LayerGetCall<'a, C, NC, A> { + self._summary_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *content version* query property to the given value. + /// + /// + /// The content version for the requested volume. + pub fn content_version(mut self, new_value: &str) -> LayerGetCall<'a, C, NC, A> { + self._content_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the volume annotations for a volume and layer. +/// +/// A builder for the *volumeAnnotations.list* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().volume_annotations_list("volumeId", "layerId", "contentVersion") +/// .volume_annotations_version("amet.") +/// .updated_min("voluptua.") +/// .updated_max("Lorem") +/// .start_position("gubergren") +/// .start_offset("justo") +/// .source("sit") +/// .show_deleted(true) +/// .page_token("diam") +/// .max_results(35) +/// .locale("consetetur") +/// .end_position("sadipscing") +/// .end_offset("vero") +/// .doit(); +/// # } +/// ``` +pub struct LayerVolumeAnnotationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _layer_id: String, + _content_version: String, + _volume_annotations_version: Option, + _updated_min: Option, + _updated_max: Option, + _start_position: Option, + _start_offset: Option, + _source: Option, + _show_deleted: Option, + _page_token: Option, + _max_results: Option, + _locale: Option, + _end_position: Option, + _end_offset: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerVolumeAnnotationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerVolumeAnnotationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumeannotations)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.volumeAnnotations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((17 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("layerId", self._layer_id.to_string())); + params.push(("contentVersion", self._content_version.to_string())); + if let Some(value) = self._volume_annotations_version { + params.push(("volumeAnnotationsVersion", value.to_string())); + } + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._updated_max { + params.push(("updatedMax", value.to_string())); + } + if let Some(value) = self._start_position { + params.push(("startPosition", value.to_string())); + } + if let Some(value) = self._start_offset { + params.push(("startOffset", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if let Some(value) = self._end_position { + params.push(("endPosition", value.to_string())); + } + if let Some(value) = self._end_offset { + params.push(("endOffset", value.to_string())); + } + for &field in ["alt", "volumeId", "layerId", "contentVersion", "volumeAnnotationsVersion", "updatedMin", "updatedMax", "startPosition", "startOffset", "source", "showDeleted", "pageToken", "maxResults", "locale", "endPosition", "endOffset"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layers/{layerId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId"), ("{layerId}", "layerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["volumeId", "layerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve annotations for. + pub fn volume_id(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *layer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the layer to get the annotations. + pub fn layer_id(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._layer_id = new_value.to_string(); + self + } + /// Sets the *content version* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The content version for the requested volume. + pub fn content_version(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._content_version = new_value.to_string(); + self + } + /// Sets the *volume annotations version* query property to the given value. + /// + /// + /// The version of the volume annotations that you are requesting. + pub fn volume_annotations_version(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._volume_annotations_version = Some(new_value.to_string()); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated since this timestamp (inclusive). + pub fn updated_min(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *updated max* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated prior to this timestamp (exclusive). + pub fn updated_max(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._updated_max = Some(new_value.to_string()); + self + } + /// Sets the *start position* query property to the given value. + /// + /// + /// The start position to start retrieving data from. + pub fn start_position(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._start_position = Some(new_value.to_string()); + self + } + /// Sets the *start offset* query property to the given value. + /// + /// + /// The start offset to start retrieving data from. + pub fn start_offset(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._start_offset = Some(new_value.to_string()); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Set to true to return deleted annotations. updatedMin must be in the request to use this. Defaults to false. + pub fn show_deleted(mut self, new_value: bool) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous page. + pub fn page_token(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale information for the data. ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. + pub fn locale(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *end position* query property to the given value. + /// + /// + /// The end position to end retrieving data from. + pub fn end_position(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._end_position = Some(new_value.to_string()); + self + } + /// Sets the *end offset* query property to the given value. + /// + /// + /// The end offset to end retrieving data from. + pub fn end_offset(mut self, new_value: &str) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._end_offset = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerVolumeAnnotationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerVolumeAnnotationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerVolumeAnnotationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the annotation data for a volume and layer. +/// +/// A builder for the *annotationData.list* method supported by a *layer* resource. +/// It is not used directly, but through a `LayerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.layers().annotation_data_list("volumeId", "layerId", "contentVersion") +/// .w(-84) +/// .updated_min("duo") +/// .updated_max("aliquyam") +/// .source("Lorem") +/// .scale(-17) +/// .page_token("clita") +/// .max_results(56) +/// .locale("takimata") +/// .h(-40) +/// .add_annotation_data_id("kasd") +/// .doit(); +/// # } +/// ``` +pub struct LayerAnnotationDataListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _layer_id: String, + _content_version: String, + _w: Option, + _updated_min: Option, + _updated_max: Option, + _source: Option, + _scale: Option, + _page_token: Option, + _max_results: Option, + _locale: Option, + _h: Option, + _annotation_data_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LayerAnnotationDataListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LayerAnnotationDataListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Annotationsdata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.layers.annotationData.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("layerId", self._layer_id.to_string())); + params.push(("contentVersion", self._content_version.to_string())); + if let Some(value) = self._w { + params.push(("w", value.to_string())); + } + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._updated_max { + params.push(("updatedMax", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._scale { + params.push(("scale", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if let Some(value) = self._h { + params.push(("h", value.to_string())); + } + if self._annotation_data_id.len() > 0 { + let mut s = String::new(); + for f in self._annotation_data_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("annotationDataId", s)); + } + for &field in ["alt", "volumeId", "layerId", "contentVersion", "w", "updatedMin", "updatedMax", "source", "scale", "pageToken", "maxResults", "locale", "h", "annotationDataId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/layers/{layerId}/data".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId"), ("{layerId}", "layerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["volumeId", "layerId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to retrieve annotation data for. + pub fn volume_id(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *layer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the layer to get the annotation data. + pub fn layer_id(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._layer_id = new_value.to_string(); + self + } + /// Sets the *content version* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The content version for the requested volume. + pub fn content_version(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._content_version = new_value.to_string(); + self + } + /// Sets the *w* query property to the given value. + /// + /// + /// The requested pixel width for any images. If width is provided height must also be provided. + pub fn w(mut self, new_value: i32) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._w = Some(new_value); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated since this timestamp (inclusive). + pub fn updated_min(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *updated max* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated prior to this timestamp (exclusive). + pub fn updated_max(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._updated_max = Some(new_value.to_string()); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *scale* query property to the given value. + /// + /// + /// The requested scale for the image. + pub fn scale(mut self, new_value: i32) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._scale = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous page. + pub fn page_token(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// The locale information for the data. ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. + pub fn locale(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *h* query property to the given value. + /// + /// + /// The requested pixel height for any images. If height is provided width must also be provided. + pub fn h(mut self, new_value: i32) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._h = Some(new_value); + self + } + /// Append the given value to the *annotation data id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The list of Annotation Data Ids to retrieve. Pagination is ignored if this is set. + pub fn add_annotation_data_id(mut self, new_value: &str) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._annotation_data_id.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LayerAnnotationDataListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LayerAnnotationDataListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LayerAnnotationDataListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Rate a recommended book for the current user. +/// +/// A builder for the *recommended.rate* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().recommended_rate("rating", "volumeId") +/// .source("At") +/// .locale("labore") +/// .doit(); +/// # } +/// ``` +pub struct VolumeRecommendedRateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _rating: String, + _volume_id: String, + _source: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeRecommendedRateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeRecommendedRateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BooksVolumesRecommendedRateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.recommended.rate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("rating", self._rating.to_string())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "rating", "volumeId", "source", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/recommended/rate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *rating* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Rating to be given to the volume. + pub fn rating(mut self, new_value: &str) -> VolumeRecommendedRateCall<'a, C, NC, A> { + self._rating = new_value.to_string(); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the source volume. + pub fn volume_id(mut self, new_value: &str) -> VolumeRecommendedRateCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeRecommendedRateCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating recommendations. + pub fn locale(mut self, new_value: &str) -> VolumeRecommendedRateCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeRecommendedRateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeRecommendedRateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeRecommendedRateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Return a list of books in My Library. +/// +/// A builder for the *mybooks.list* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().mybooks_list() +/// .start_index(64) +/// .source("ea") +/// .add_processing_state("sadipscing") +/// .max_results(35) +/// .locale("dolore") +/// .add_acquire_method("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct VolumeMybookListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _start_index: Option, + _source: Option, + _processing_state: Vec, + _max_results: Option, + _locale: Option, + _acquire_method: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeMybookListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeMybookListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.mybooks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if self._processing_state.len() > 0 { + let mut s = String::new(); + for f in self._processing_state.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("processingState", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._acquire_method.len() > 0 { + let mut s = String::new(); + for f in self._acquire_method.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("acquireMethod", s)); + } + for &field in ["alt", "startIndex", "source", "processingState", "maxResults", "locale", "acquireMethod"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/mybooks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first result to return (starts at 0) + pub fn start_index(mut self, new_value: u32) -> VolumeMybookListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeMybookListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Append the given value to the *processing state* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The processing state of the user uploaded volumes to be returned. Applicable only if the UPLOADED is specified in the acquireMethod. + pub fn add_processing_state(mut self, new_value: &str) -> VolumeMybookListCall<'a, C, NC, A> { + self._processing_state.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: u32) -> VolumeMybookListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Ex:'en_US'. Used for generating recommendations. + pub fn locale(mut self, new_value: &str) -> VolumeMybookListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *acquire method* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// How the book was aquired + pub fn add_acquire_method(mut self, new_value: &str) -> VolumeMybookListCall<'a, C, NC, A> { + self._acquire_method.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeMybookListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeMybookListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeMybookListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Performs a book search. +/// +/// A builder for the *list* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().list("q") +/// .start_index(19) +/// .source("sit") +/// .show_preorders(true) +/// .projection("consetetur") +/// .print_type("labore") +/// .partner("sed") +/// .order_by("ea") +/// .max_results(39) +/// .library_restrict("aliquyam") +/// .lang_restrict("eos") +/// .filter("tempor") +/// .download("sea") +/// .doit(); +/// # } +/// ``` +pub struct VolumeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _q: String, + _start_index: Option, + _source: Option, + _show_preorders: Option, + _projection: Option, + _print_type: Option, + _partner: Option, + _order_by: Option, + _max_results: Option, + _library_restrict: Option, + _lang_restrict: Option, + _filter: Option, + _download: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + params.push(("q", self._q.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_preorders { + params.push(("showPreorders", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._print_type { + params.push(("printType", value.to_string())); + } + if let Some(value) = self._partner { + params.push(("partner", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._library_restrict { + params.push(("libraryRestrict", value.to_string())); + } + if let Some(value) = self._lang_restrict { + params.push(("langRestrict", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + if let Some(value) = self._download { + params.push(("download", value.to_string())); + } + for &field in ["alt", "q", "startIndex", "source", "showPreorders", "projection", "printType", "partner", "orderBy", "maxResults", "libraryRestrict", "langRestrict", "filter", "download"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *q* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Full-text search query string. + pub fn q(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._q = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first result to return (starts at 0) + pub fn start_index(mut self, new_value: u32) -> VolumeListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show preorders* query property to the given value. + /// + /// + /// Set to true to show books available for preorder. Defaults to false. + pub fn show_preorders(mut self, new_value: bool) -> VolumeListCall<'a, C, NC, A> { + self._show_preorders = Some(new_value); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *print type* query property to the given value. + /// + /// + /// Restrict to books or magazines. + pub fn print_type(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._print_type = Some(new_value.to_string()); + self + } + /// Sets the *partner* query property to the given value. + /// + /// + /// Restrict and brand results for partner ID. + pub fn partner(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._partner = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// Sort search results. + pub fn order_by(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: u32) -> VolumeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *library restrict* query property to the given value. + /// + /// + /// Restrict search to this user's library. + pub fn library_restrict(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._library_restrict = Some(new_value.to_string()); + self + } + /// Sets the *lang restrict* query property to the given value. + /// + /// + /// Restrict results to books with this language code. + pub fn lang_restrict(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._lang_restrict = Some(new_value.to_string()); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Filter search results. + pub fn filter(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *download* query property to the given value. + /// + /// + /// Restrict to volumes by download availability. + pub fn download(mut self, new_value: &str) -> VolumeListCall<'a, C, NC, A> { + self._download = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Return a list of books uploaded by the current user. +/// +/// A builder for the *useruploaded.list* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().useruploaded_list() +/// .add_volume_id("labore") +/// .start_index(47) +/// .source("aliquyam") +/// .add_processing_state("dolores") +/// .max_results(3) +/// .locale("diam") +/// .doit(); +/// # } +/// ``` +pub struct VolumeUseruploadedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: Vec, + _start_index: Option, + _source: Option, + _processing_state: Vec, + _max_results: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeUseruploadedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeUseruploadedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.useruploaded.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if self._volume_id.len() > 0 { + let mut s = String::new(); + for f in self._volume_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("volumeId", s)); + } + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if self._processing_state.len() > 0 { + let mut s = String::new(); + for f in self._processing_state.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("processingState", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "volumeId", "startIndex", "source", "processingState", "maxResults", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/useruploaded".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *volume id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The ids of the volumes to be returned. If not specified all that match the processingState are returned. + pub fn add_volume_id(mut self, new_value: &str) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._volume_id.push(new_value.to_string()); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first result to return (starts at 0) + pub fn start_index(mut self, new_value: u32) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Append the given value to the *processing state* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The processing state of the user uploaded volumes to be returned. + pub fn add_processing_state(mut self, new_value: &str) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._processing_state.push(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: u32) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating recommendations. + pub fn locale(mut self, new_value: &str) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeUseruploadedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeUseruploadedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeUseruploadedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Return a list of associated books. +/// +/// A builder for the *associated.list* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().associated_list("volumeId") +/// .source("justo") +/// .locale("est") +/// .association("amet") +/// .doit(); +/// # } +/// ``` +pub struct VolumeAssociatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _source: Option, + _locale: Option, + _association: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeAssociatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeAssociatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.associated.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if let Some(value) = self._association { + params.push(("association", value.to_string())); + } + for &field in ["alt", "volumeId", "source", "locale", "association"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}/associated".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["volumeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the source volume. + pub fn volume_id(mut self, new_value: &str) -> VolumeAssociatedListCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeAssociatedListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating recommendations. + pub fn locale(mut self, new_value: &str) -> VolumeAssociatedListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *association* query property to the given value. + /// + /// + /// Association type. + pub fn association(mut self, new_value: &str) -> VolumeAssociatedListCall<'a, C, NC, A> { + self._association = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeAssociatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeAssociatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeAssociatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets volume information for a single volume. +/// +/// A builder for the *get* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().get("volumeId") +/// .user_library_consistent_read(true) +/// .source("diam") +/// .projection("justo") +/// .partner("est") +/// .country("clita") +/// .doit(); +/// # } +/// ``` +pub struct VolumeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _user_library_consistent_read: Option, + _source: Option, + _projection: Option, + _partner: Option, + _country: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volume)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._user_library_consistent_read { + params.push(("user_library_consistent_read", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._partner { + params.push(("partner", value.to_string())); + } + if let Some(value) = self._country { + params.push(("country", value.to_string())); + } + for &field in ["alt", "volumeId", "user_library_consistent_read", "source", "projection", "partner", "country"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/{volumeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["volumeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume to retrieve. + pub fn volume_id(mut self, new_value: &str) -> VolumeGetCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *user_library_consistent_read* query property to the given value. + /// + /// + pub fn user_library_consistent_read(mut self, new_value: bool) -> VolumeGetCall<'a, C, NC, A> { + self._user_library_consistent_read = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> VolumeGetCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *partner* query property to the given value. + /// + /// + /// Brand results for partner ID. + pub fn partner(mut self, new_value: &str) -> VolumeGetCall<'a, C, NC, A> { + self._partner = Some(new_value.to_string()); + self + } + /// Sets the *country* query property to the given value. + /// + /// + /// ISO-3166-1 code to override the IP-based location. + pub fn country(mut self, new_value: &str) -> VolumeGetCall<'a, C, NC, A> { + self._country = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Return a list of recommended books for the current user. +/// +/// A builder for the *recommended.list* method supported by a *volume* resource. +/// It is not used directly, but through a `VolumeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.volumes().recommended_list() +/// .source("invidunt") +/// .locale("ut") +/// .doit(); +/// # } +/// ``` +pub struct VolumeRecommendedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _source: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for VolumeRecommendedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> VolumeRecommendedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.volumes.recommended.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "source", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/volumes/recommended".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> VolumeRecommendedListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating recommendations. + pub fn locale(mut self, new_value: &str) -> VolumeRecommendedListCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeRecommendedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VolumeRecommendedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VolumeRecommendedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a list of offline dictionary meatadata available +/// +/// A builder for the *listOfflineMetadata* method supported by a *dictionary* resource. +/// It is not used directly, but through a `DictionaryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.dictionary().list_offline_metadata("cpksver") +/// .doit(); +/// # } +/// ``` +pub struct DictionaryListOfflineMetadataCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _cpksver: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DictionaryListOfflineMetadataCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DictionaryListOfflineMetadataCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Metadata)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.dictionary.listOfflineMetadata", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("cpksver", self._cpksver.to_string())); + for &field in ["alt", "cpksver"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/dictionary/listOfflineMetadata".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *cpksver* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The device/version ID from which to request the data. + pub fn cpksver(mut self, new_value: &str) -> DictionaryListOfflineMetadataCall<'a, C, NC, A> { + self._cpksver = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DictionaryListOfflineMetadataCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DictionaryListOfflineMetadataCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DictionaryListOfflineMetadataCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves volumes in a specific bookshelf for the specified user. +/// +/// A builder for the *volumes.list* method supported by a *bookshelve* resource. +/// It is not used directly, but through a `BookshelveMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.bookshelves().volumes_list("userId", "shelf") +/// .start_index(82) +/// .source("sed") +/// .show_preorders(true) +/// .max_results(34) +/// .doit(); +/// # } +/// ``` +pub struct BookshelveVolumeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _user_id: String, + _shelf: String, + _start_index: Option, + _source: Option, + _show_preorders: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BookshelveVolumeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BookshelveVolumeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.bookshelves.volumes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("shelf", self._shelf.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_preorders { + params.push(("showPreorders", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "userId", "shelf", "startIndex", "source", "showPreorders", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/users/{userId}/bookshelves/{shelf}/volumes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of user for whom to retrieve bookshelf volumes. + pub fn user_id(mut self, new_value: &str) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf to retrieve volumes. + pub fn shelf(mut self, new_value: &str) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first element to return (starts at 0) + pub fn start_index(mut self, new_value: u32) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show preorders* query property to the given value. + /// + /// + /// Set to true to show pre-ordered books. Defaults to false. + pub fn show_preorders(mut self, new_value: bool) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._show_preorders = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BookshelveVolumeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BookshelveVolumeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BookshelveVolumeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of public bookshelves for the specified user. +/// +/// A builder for the *list* method supported by a *bookshelve* resource. +/// It is not used directly, but through a `BookshelveMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.bookshelves().list("userId") +/// .source("et") +/// .doit(); +/// # } +/// ``` +pub struct BookshelveListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _user_id: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BookshelveListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BookshelveListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Bookshelves)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.bookshelves.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["alt", "userId", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/users/{userId}/bookshelves".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of user for whom to retrieve bookshelves. + pub fn user_id(mut self, new_value: &str) -> BookshelveListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> BookshelveListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BookshelveListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BookshelveListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BookshelveListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves metadata for a specific bookshelf for the specified user. +/// +/// A builder for the *get* method supported by a *bookshelve* resource. +/// It is not used directly, but through a `BookshelveMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.bookshelves().get("userId", "shelf") +/// .source("kasd") +/// .doit(); +/// # } +/// ``` +pub struct BookshelveGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _user_id: String, + _shelf: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BookshelveGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BookshelveGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Bookshelf)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.bookshelves.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("shelf", self._shelf.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["alt", "userId", "shelf", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/users/{userId}/bookshelves/{shelf}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of user for whom to retrieve bookshelves. + pub fn user_id(mut self, new_value: &str) -> BookshelveGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf to retrieve. + pub fn shelf(mut self, new_value: &str) -> BookshelveGetCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> BookshelveGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BookshelveGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BookshelveGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BookshelveGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// +/// +/// A builder for the *accept* method supported by a *promooffer* resource. +/// It is not used directly, but through a `PromoofferMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.promooffer().accept() +/// .volume_id("invidunt") +/// .serial("rebum.") +/// .product("Lorem") +/// .offer_id("clita") +/// .model("invidunt") +/// .manufacturer("eirmod") +/// .device("At") +/// .android_id("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct PromoofferAcceptCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: Option, + _serial: Option, + _product: Option, + _offer_id: Option, + _model: Option, + _manufacturer: Option, + _device: Option, + _android_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PromoofferAcceptCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PromoofferAcceptCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.promooffer.accept", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + if let Some(value) = self._volume_id { + params.push(("volumeId", value.to_string())); + } + if let Some(value) = self._serial { + params.push(("serial", value.to_string())); + } + if let Some(value) = self._product { + params.push(("product", value.to_string())); + } + if let Some(value) = self._offer_id { + params.push(("offerId", value.to_string())); + } + if let Some(value) = self._model { + params.push(("model", value.to_string())); + } + if let Some(value) = self._manufacturer { + params.push(("manufacturer", value.to_string())); + } + if let Some(value) = self._device { + params.push(("device", value.to_string())); + } + if let Some(value) = self._android_id { + params.push(("androidId", value.to_string())); + } + for &field in ["volumeId", "serial", "product", "offerId", "model", "manufacturer", "device", "androidId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/promooffer/accept".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* query property to the given value. + /// + /// + /// Volume id to exercise the offer + pub fn volume_id(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._volume_id = Some(new_value.to_string()); + self + } + /// Sets the *serial* query property to the given value. + /// + /// + /// device serial + pub fn serial(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._serial = Some(new_value.to_string()); + self + } + /// Sets the *product* query property to the given value. + /// + /// + /// device product + pub fn product(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._product = Some(new_value.to_string()); + self + } + /// Sets the *offer id* query property to the given value. + /// + /// + pub fn offer_id(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._offer_id = Some(new_value.to_string()); + self + } + /// Sets the *model* query property to the given value. + /// + /// + /// device model + pub fn model(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._model = Some(new_value.to_string()); + self + } + /// Sets the *manufacturer* query property to the given value. + /// + /// + /// device manufacturer + pub fn manufacturer(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._manufacturer = Some(new_value.to_string()); + self + } + /// Sets the *device* query property to the given value. + /// + /// + /// device device + pub fn device(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._device = Some(new_value.to_string()); + self + } + /// Sets the *android id* query property to the given value. + /// + /// + /// device android_id + pub fn android_id(mut self, new_value: &str) -> PromoofferAcceptCall<'a, C, NC, A> { + self._android_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PromoofferAcceptCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PromoofferAcceptCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PromoofferAcceptCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// +/// +/// A builder for the *dismiss* method supported by a *promooffer* resource. +/// It is not used directly, but through a `PromoofferMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.promooffer().dismiss() +/// .serial("et") +/// .product("sed") +/// .offer_id("sit") +/// .model("takimata") +/// .manufacturer("elitr") +/// .device("nonumy") +/// .android_id("rebum.") +/// .doit(); +/// # } +/// ``` +pub struct PromoofferDismisCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _serial: Option, + _product: Option, + _offer_id: Option, + _model: Option, + _manufacturer: Option, + _device: Option, + _android_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PromoofferDismisCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PromoofferDismisCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.promooffer.dismiss", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if let Some(value) = self._serial { + params.push(("serial", value.to_string())); + } + if let Some(value) = self._product { + params.push(("product", value.to_string())); + } + if let Some(value) = self._offer_id { + params.push(("offerId", value.to_string())); + } + if let Some(value) = self._model { + params.push(("model", value.to_string())); + } + if let Some(value) = self._manufacturer { + params.push(("manufacturer", value.to_string())); + } + if let Some(value) = self._device { + params.push(("device", value.to_string())); + } + if let Some(value) = self._android_id { + params.push(("androidId", value.to_string())); + } + for &field in ["serial", "product", "offerId", "model", "manufacturer", "device", "androidId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/promooffer/dismiss".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *serial* query property to the given value. + /// + /// + /// device serial + pub fn serial(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._serial = Some(new_value.to_string()); + self + } + /// Sets the *product* query property to the given value. + /// + /// + /// device product + pub fn product(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._product = Some(new_value.to_string()); + self + } + /// Sets the *offer id* query property to the given value. + /// + /// + /// Offer to dimiss + pub fn offer_id(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._offer_id = Some(new_value.to_string()); + self + } + /// Sets the *model* query property to the given value. + /// + /// + /// device model + pub fn model(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._model = Some(new_value.to_string()); + self + } + /// Sets the *manufacturer* query property to the given value. + /// + /// + /// device manufacturer + pub fn manufacturer(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._manufacturer = Some(new_value.to_string()); + self + } + /// Sets the *device* query property to the given value. + /// + /// + /// device device + pub fn device(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._device = Some(new_value.to_string()); + self + } + /// Sets the *android id* query property to the given value. + /// + /// + /// device android_id + pub fn android_id(mut self, new_value: &str) -> PromoofferDismisCall<'a, C, NC, A> { + self._android_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PromoofferDismisCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PromoofferDismisCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PromoofferDismisCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a list of promo offers available to the user +/// +/// A builder for the *get* method supported by a *promooffer* resource. +/// It is not used directly, but through a `PromoofferMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.promooffer().get() +/// .serial("Lorem") +/// .product("Lorem") +/// .model("diam") +/// .manufacturer("ut") +/// .device("ut") +/// .android_id("amet.") +/// .doit(); +/// # } +/// ``` +pub struct PromoofferGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _serial: Option, + _product: Option, + _model: Option, + _manufacturer: Option, + _device: Option, + _android_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PromoofferGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PromoofferGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Offers)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.promooffer.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if let Some(value) = self._serial { + params.push(("serial", value.to_string())); + } + if let Some(value) = self._product { + params.push(("product", value.to_string())); + } + if let Some(value) = self._model { + params.push(("model", value.to_string())); + } + if let Some(value) = self._manufacturer { + params.push(("manufacturer", value.to_string())); + } + if let Some(value) = self._device { + params.push(("device", value.to_string())); + } + if let Some(value) = self._android_id { + params.push(("androidId", value.to_string())); + } + for &field in ["alt", "serial", "product", "model", "manufacturer", "device", "androidId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/promooffer/get".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *serial* query property to the given value. + /// + /// + /// device serial + pub fn serial(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._serial = Some(new_value.to_string()); + self + } + /// Sets the *product* query property to the given value. + /// + /// + /// device product + pub fn product(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._product = Some(new_value.to_string()); + self + } + /// Sets the *model* query property to the given value. + /// + /// + /// device model + pub fn model(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._model = Some(new_value.to_string()); + self + } + /// Sets the *manufacturer* query property to the given value. + /// + /// + /// device manufacturer + pub fn manufacturer(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._manufacturer = Some(new_value.to_string()); + self + } + /// Sets the *device* query property to the given value. + /// + /// + /// device device + pub fn device(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._device = Some(new_value.to_string()); + self + } + /// Sets the *android id* query property to the given value. + /// + /// + /// device android_id + pub fn android_id(mut self, new_value: &str) -> PromoofferGetCall<'a, C, NC, A> { + self._android_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PromoofferGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PromoofferGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PromoofferGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List categories for onboarding experience. +/// +/// A builder for the *listCategories* method supported by a *onboarding* resource. +/// It is not used directly, but through a `OnboardingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.onboarding().list_categories() +/// .locale("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct OnboardingListCategoryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OnboardingListCategoryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OnboardingListCategoryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Category)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.onboarding.listCategories", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/onboarding/listCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Default is en-US if unset. + pub fn locale(mut self, new_value: &str) -> OnboardingListCategoryCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OnboardingListCategoryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OnboardingListCategoryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OnboardingListCategoryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List available volumes under categories for onboarding experience. +/// +/// A builder for the *listCategoryVolumes* method supported by a *onboarding* resource. +/// It is not used directly, but through a `OnboardingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.onboarding().list_category_volumes() +/// .page_token("ut") +/// .page_size(98) +/// .locale("sea") +/// .add_category_id("ut") +/// .doit(); +/// # } +/// ``` +pub struct OnboardingListCategoryVolumeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _page_token: Option, + _page_size: Option, + _locale: Option, + _category_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OnboardingListCategoryVolumeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OnboardingListCategoryVolumeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volume2)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.onboarding.listCategoryVolumes", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._page_size { + params.push(("pageSize", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._category_id.len() > 0 { + let mut s = String::new(); + for f in self._category_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("categoryId", s)); + } + for &field in ["alt", "pageToken", "pageSize", "locale", "categoryId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/onboarding/listCategoryVolumes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous page. + pub fn page_token(mut self, new_value: &str) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *page size* query property to the given value. + /// + /// + /// Number of maximum results per page to be included in the response. + pub fn page_size(mut self, new_value: u32) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + self._page_size = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1 language and ISO-3166-1 country code. Default is en-US if unset. + pub fn locale(mut self, new_value: &str) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *category id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// List of category ids requested. + pub fn add_category_id(mut self, new_value: &str) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + self._category_id.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OnboardingListCategoryVolumeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Request concurrent and download access restrictions. +/// +/// A builder for the *requestAccess* method supported by a *myconfig* resource. +/// It is not used directly, but through a `MyconfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.myconfig().request_access("source", "volumeId", "nonce", "cpksver") +/// .locale("et") +/// .license_types("et") +/// .doit(); +/// # } +/// ``` +pub struct MyconfigRequestAccesCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _source: String, + _volume_id: String, + _nonce: String, + _cpksver: String, + _locale: Option, + _license_types: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MyconfigRequestAccesCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigRequestAccesCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RequestAccess)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.myconfig.requestAccess", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("source", self._source.to_string())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("nonce", self._nonce.to_string())); + params.push(("cpksver", self._cpksver.to_string())); + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if let Some(value) = self._license_types { + params.push(("licenseTypes", value.to_string())); + } + for &field in ["alt", "source", "volumeId", "nonce", "cpksver", "locale", "licenseTypes"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/myconfig/requestAccess".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *source* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._source = new_value.to_string(); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume to request concurrent/download restrictions for. + pub fn volume_id(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *nonce* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The client nonce value. + pub fn nonce(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._nonce = new_value.to_string(); + self + } + /// Sets the *cpksver* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The device/version ID from which to request the restrictions. + pub fn cpksver(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._cpksver = new_value.to_string(); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US. + pub fn locale(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *license types* query property to the given value. + /// + /// + /// The type of access license to request. If not specified, the default is BOTH. + pub fn license_types(mut self, new_value: &str) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._license_types = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MyconfigRequestAccesCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MyconfigRequestAccesCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MyconfigRequestAccesCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Release downloaded content access restriction. +/// +/// A builder for the *releaseDownloadAccess* method supported by a *myconfig* resource. +/// It is not used directly, but through a `MyconfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.myconfig().release_download_access("volumeIds", "cpksver") +/// .source("sed") +/// .locale("et") +/// .doit(); +/// # } +/// ``` +pub struct MyconfigReleaseDownloadAccesCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_ids: Vec, + _cpksver: String, + _source: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MyconfigReleaseDownloadAccesCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DownloadAccesses)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.myconfig.releaseDownloadAccess", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if self._volume_ids.len() > 0 { + let mut s = String::new(); + for f in self._volume_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("volumeIds", s)); + } + params.push(("cpksver", self._cpksver.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "volumeIds", "cpksver", "source", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/myconfig/releaseDownloadAccess".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *volume ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The volume(s) to release restrictions for. + pub fn add_volume_ids(mut self, new_value: &str) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + self._volume_ids.push(new_value.to_string()); + self + } + /// Sets the *cpksver* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The device/version ID from which to release the restriction. + pub fn cpksver(mut self, new_value: &str) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + self._cpksver = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US. + pub fn locale(mut self, new_value: &str) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MyconfigReleaseDownloadAccesCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Request downloaded content access for specified volumes on the My eBooks shelf. +/// +/// A builder for the *syncVolumeLicenses* method supported by a *myconfig* resource. +/// It is not used directly, but through a `MyconfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.myconfig().sync_volume_licenses("source", "nonce", "cpksver") +/// .add_volume_ids("vero") +/// .show_preorders(false) +/// .locale("takimata") +/// .add_features("et") +/// .doit(); +/// # } +/// ``` +pub struct MyconfigSyncVolumeLicenseCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _source: String, + _nonce: String, + _cpksver: String, + _volume_ids: Vec, + _show_preorders: Option, + _locale: Option, + _features: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MyconfigSyncVolumeLicenseCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.myconfig.syncVolumeLicenses", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("source", self._source.to_string())); + params.push(("nonce", self._nonce.to_string())); + params.push(("cpksver", self._cpksver.to_string())); + if self._volume_ids.len() > 0 { + let mut s = String::new(); + for f in self._volume_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("volumeIds", s)); + } + if let Some(value) = self._show_preorders { + params.push(("showPreorders", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + if self._features.len() > 0 { + let mut s = String::new(); + for f in self._features.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("features", s)); + } + for &field in ["alt", "source", "nonce", "cpksver", "volumeIds", "showPreorders", "locale", "features"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/myconfig/syncVolumeLicenses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *source* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._source = new_value.to_string(); + self + } + /// Sets the *nonce* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The client nonce value. + pub fn nonce(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._nonce = new_value.to_string(); + self + } + /// Sets the *cpksver* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The device/version ID from which to release the restriction. + pub fn cpksver(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._cpksver = new_value.to_string(); + self + } + /// Append the given value to the *volume ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The volume(s) to request download restrictions for. + pub fn add_volume_ids(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._volume_ids.push(new_value.to_string()); + self + } + /// Sets the *show preorders* query property to the given value. + /// + /// + /// Set to true to show pre-ordered books. Defaults to false. + pub fn show_preorders(mut self, new_value: bool) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._show_preorders = Some(new_value); + self + } + /// Sets the *locale* query property to the given value. + /// + /// + /// ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US. + pub fn locale(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._locale = Some(new_value.to_string()); + self + } + /// Append the given value to the *features* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// List of features supported by the client, i.e., 'RENTALS' + pub fn add_features(mut self, new_value: &str) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._features.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MyconfigSyncVolumeLicenseCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the current settings for the user. +/// +/// A builder for the *getUserSettings* method supported by a *myconfig* resource. +/// It is not used directly, but through a `MyconfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.myconfig().get_user_settings() +/// .doit(); +/// # } +/// ``` +pub struct MyconfigGetUserSettingCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MyconfigGetUserSettingCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigGetUserSettingCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Usersettings)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.myconfig.getUserSettings", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/myconfig/getUserSettings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MyconfigGetUserSettingCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MyconfigGetUserSettingCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MyconfigGetUserSettingCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets the settings for the user. Unspecified sub-objects will retain the existing value. +/// +/// A builder for the *updateUserSettings* method supported by a *myconfig* resource. +/// It is not used directly, but through a `MyconfigMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// use books1::Usersettings; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Usersettings = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.myconfig().update_user_settings(&req) +/// .doit(); +/// # } +/// ``` +pub struct MyconfigUpdateUserSettingCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _request: Usersettings, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MyconfigUpdateUserSettingCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MyconfigUpdateUserSettingCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Usersettings)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.myconfig.updateUserSettings", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/myconfig/updateUserSettings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Usersettings) -> MyconfigUpdateUserSettingCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MyconfigUpdateUserSettingCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MyconfigUpdateUserSettingCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MyconfigUpdateUserSettingCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Clears all volumes from a bookshelf. +/// +/// A builder for the *bookshelves.clearVolumes* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_clear_volumes("shelf") +/// .source("et") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveClearVolumeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveClearVolumeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.clearVolumes", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["shelf", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}/clearVolumes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf from which to remove a volume. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveClearVolumeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Moves a volume within a bookshelf. +/// +/// A builder for the *bookshelves.moveVolume* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_move_volume("shelf", "volumeId", -38) +/// .source("rebum.") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _volume_id: String, + _volume_position: i32, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.moveVolume", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("volumePosition", self._volume_position.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["shelf", "volumeId", "volumePosition", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}/moveVolume".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf with the volume. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume to move. + pub fn volume_id(mut self, new_value: &str) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *volume position* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Position on shelf to move the item (0 puts the item before the current first item, 1 puts it between the first and the second and so on.) + pub fn volume_position(mut self, new_value: i32) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + self._volume_position = new_value; + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveMoveVolumeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets volume information for volumes on a bookshelf. +/// +/// A builder for the *bookshelves.volumes.list* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_volumes_list("shelf") +/// .start_index(19) +/// .source("elitr") +/// .show_preorders(true) +/// .q("sea") +/// .projection("elitr") +/// .max_results(24) +/// .country("sea") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveVolumeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _start_index: Option, + _source: Option, + _show_preorders: Option, + _q: Option, + _projection: Option, + _max_results: Option, + _country: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveVolumeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveVolumeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Volumes)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.volumes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + if let Some(value) = self._start_index { + params.push(("startIndex", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_preorders { + params.push(("showPreorders", value.to_string())); + } + if let Some(value) = self._q { + params.push(("q", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._country { + params.push(("country", value.to_string())); + } + for &field in ["alt", "shelf", "startIndex", "source", "showPreorders", "q", "projection", "maxResults", "country"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}/volumes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The bookshelf ID or name retrieve volumes for. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *start index* query property to the given value. + /// + /// + /// Index of the first element to return (starts at 0) + pub fn start_index(mut self, new_value: u32) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._start_index = Some(new_value); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show preorders* query property to the given value. + /// + /// + /// Set to true to show pre-ordered books. Defaults to false. + pub fn show_preorders(mut self, new_value: bool) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._show_preorders = Some(new_value); + self + } + /// Sets the *q* query property to the given value. + /// + /// + /// Full-text search query string in this bookshelf. + pub fn q(mut self, new_value: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._q = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// Restrict information returned to a set of selected fields. + pub fn projection(mut self, new_value: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *country* query property to the given value. + /// + /// + /// ISO-3166-1 code to override the IP-based location. + pub fn country(mut self, new_value: &str) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._country = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveVolumeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the summary of specified layers. +/// +/// A builder for the *annotations.summary* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().annotations_summary("layerIds", "volumeId") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryAnnotationSummaryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _layer_ids: Vec, + _volume_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryAnnotationSummaryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryAnnotationSummaryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AnnotationsSummary)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.annotations.summary", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if self._layer_ids.len() > 0 { + let mut s = String::new(); + for f in self._layer_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("layerIds", s)); + } + params.push(("volumeId", self._volume_id.to_string())); + for &field in ["alt", "layerIds", "volumeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/annotations/summary".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *layer ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Array of layer IDs to get the summary for. + pub fn add_layer_ids(mut self, new_value: &str) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> { + self._layer_ids.push(new_value.to_string()); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Volume id to get the summary for. + pub fn volume_id(mut self, new_value: &str) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryAnnotationSummaryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an annotation. +/// +/// A builder for the *annotations.delete* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().annotations_delete("annotationId") +/// .source("dolores") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryAnnotationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _annotation_id: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryAnnotationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryAnnotationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.annotations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("annotationId", self._annotation_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["annotationId", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/annotations/{annotationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{annotationId}", "annotationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["annotationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *annotation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the annotation to delete. + pub fn annotation_id(mut self, new_value: &str) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> { + self._annotation_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryAnnotationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a volume to a bookshelf. +/// +/// A builder for the *bookshelves.addVolume* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_add_volume("shelf", "volumeId") +/// .source("aliquyam") +/// .reason("elitr") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveAddVolumeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _volume_id: String, + _source: Option, + _reason: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveAddVolumeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.addVolume", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._reason { + params.push(("reason", value.to_string())); + } + for &field in ["shelf", "volumeId", "source", "reason"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}/addVolume".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf to which to add a volume. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume to add. + pub fn volume_id(mut self, new_value: &str) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *reason* query property to the given value. + /// + /// + /// The reason for which the book is added to the library. + pub fn reason(mut self, new_value: &str) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + self._reason = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveAddVolumeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new annotation. +/// +/// A builder for the *annotations.insert* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// use books1::Annotation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Annotation = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().annotations_insert(&req) +/// .source("ea") +/// .show_only_summary_in_response(true) +/// .country("Stet") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryAnnotationInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _request: Annotation, + _source: Option, + _show_only_summary_in_response: Option, + _country: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryAnnotationInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryAnnotationInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Annotation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.annotations.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_only_summary_in_response { + params.push(("showOnlySummaryInResponse", value.to_string())); + } + if let Some(value) = self._country { + params.push(("country", value.to_string())); + } + for &field in ["alt", "source", "showOnlySummaryInResponse", "country"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/annotations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Annotation) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show only summary in response* query property to the given value. + /// + /// + /// Requests that only the summary of the specified layer be provided in the response. + pub fn show_only_summary_in_response(mut self, new_value: bool) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + self._show_only_summary_in_response = Some(new_value); + self + } + /// Sets the *country* query property to the given value. + /// + /// + /// ISO-3166-1 code to override the IP-based location. + pub fn country(mut self, new_value: &str) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + self._country = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryAnnotationInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryAnnotationInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryAnnotationInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a volume from a bookshelf. +/// +/// A builder for the *bookshelves.removeVolume* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_remove_volume("shelf", "volumeId") +/// .source("sanctus") +/// .reason("dolore") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _volume_id: String, + _source: Option, + _reason: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.removeVolume", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._reason { + params.push(("reason", value.to_string())); + } + for &field in ["shelf", "volumeId", "source", "reason"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}/removeVolume".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf from which to remove a volume. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume to remove. + pub fn volume_id(mut self, new_value: &str) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *reason* query property to the given value. + /// + /// + /// The reason for which the book is removed from the library. + pub fn reason(mut self, new_value: &str) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + self._reason = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveRemoveVolumeCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of annotations, possibly filtered. +/// +/// A builder for the *annotations.list* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().annotations_list() +/// .volume_id("Lorem") +/// .updated_min("consetetur") +/// .updated_max("consetetur") +/// .source("eirmod") +/// .show_deleted(true) +/// .page_token("gubergren") +/// .max_results(28) +/// .add_layer_ids("sadipscing") +/// .layer_id("accusam") +/// .content_version("magna") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryAnnotationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: Option, + _updated_min: Option, + _updated_max: Option, + _source: Option, + _show_deleted: Option, + _page_token: Option, + _max_results: Option, + _layer_ids: Vec, + _layer_id: Option, + _content_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryAnnotationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryAnnotationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Annotations)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.annotations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + if let Some(value) = self._volume_id { + params.push(("volumeId", value.to_string())); + } + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._updated_max { + params.push(("updatedMax", value.to_string())); + } + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._layer_ids.len() > 0 { + let mut s = String::new(); + for f in self._layer_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("layerIds", s)); + } + if let Some(value) = self._layer_id { + params.push(("layerId", value.to_string())); + } + if let Some(value) = self._content_version { + params.push(("contentVersion", value.to_string())); + } + for &field in ["alt", "volumeId", "updatedMin", "updatedMax", "source", "showDeleted", "pageToken", "maxResults", "layerIds", "layerId", "contentVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/annotations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* query property to the given value. + /// + /// + /// The volume to restrict annotations to. + pub fn volume_id(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._volume_id = Some(new_value.to_string()); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated since this timestamp (inclusive). + pub fn updated_min(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *updated max* query property to the given value. + /// + /// + /// RFC 3339 timestamp to restrict to items updated prior to this timestamp (exclusive). + pub fn updated_max(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._updated_max = Some(new_value.to_string()); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Set to true to return deleted annotations. updatedMin must be in the request to use this. Defaults to false. + pub fn show_deleted(mut self, new_value: bool) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous page. + pub fn page_token(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return + pub fn max_results(mut self, new_value: u32) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *layer ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The layer ID(s) to limit annotation by. + pub fn add_layer_ids(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._layer_ids.push(new_value.to_string()); + self + } + /// Sets the *layer id* query property to the given value. + /// + /// + /// The layer ID to limit annotation by. + pub fn layer_id(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._layer_id = Some(new_value.to_string()); + self + } + /// Sets the *content version* query property to the given value. + /// + /// + /// The content version for the requested volume. + pub fn content_version(mut self, new_value: &str) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._content_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryAnnotationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryAnnotationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryAnnotationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing annotation. +/// +/// A builder for the *annotations.update* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// use books1::Annotation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Annotation = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().annotations_update(&req, "annotationId") +/// .source("rebum.") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryAnnotationUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _request: Annotation, + _annotation_id: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryAnnotationUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryAnnotationUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Annotation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.annotations.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("annotationId", self._annotation_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["alt", "annotationId", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/annotations/{annotationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{annotationId}", "annotationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["annotationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Annotation) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *annotation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the annotation to update. + pub fn annotation_id(mut self, new_value: &str) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> { + self._annotation_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryAnnotationUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets my reading position information for a volume. +/// +/// A builder for the *readingpositions.setPosition* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().readingpositions_set_position("volumeId", "timestamp", "position") +/// .source("dolores") +/// .device_cookie("vero") +/// .content_version("consetetur") +/// .action("vero") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryReadingpositionSetPositionCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _timestamp: String, + _position: String, + _source: Option, + _device_cookie: Option, + _content_version: Option, + _action: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryReadingpositionSetPositionCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.readingpositions.setPosition", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + params.push(("timestamp", self._timestamp.to_string())); + params.push(("position", self._position.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._device_cookie { + params.push(("deviceCookie", value.to_string())); + } + if let Some(value) = self._content_version { + params.push(("contentVersion", value.to_string())); + } + if let Some(value) = self._action { + params.push(("action", value.to_string())); + } + for &field in ["volumeId", "timestamp", "position", "source", "deviceCookie", "contentVersion", "action"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/readingpositions/{volumeId}/setPosition".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["volumeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume for which to update the reading position. + pub fn volume_id(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *timestamp* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// RFC 3339 UTC format timestamp associated with this reading position. + pub fn timestamp(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._timestamp = new_value.to_string(); + self + } + /// Sets the *position* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Position string for the new volume reading position. + pub fn position(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._position = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *device cookie* query property to the given value. + /// + /// + /// Random persistent device cookie optional on set position. + pub fn device_cookie(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._device_cookie = Some(new_value.to_string()); + self + } + /// Sets the *content version* query property to the given value. + /// + /// + /// Volume content version for which this reading position applies. + pub fn content_version(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._content_version = Some(new_value.to_string()); + self + } + /// Sets the *action* query property to the given value. + /// + /// + /// Action that caused this reading position to be set. + pub fn action(mut self, new_value: &str) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._action = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryReadingpositionSetPositionCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves metadata for a specific bookshelf belonging to the authenticated user. +/// +/// A builder for the *bookshelves.get* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_get("shelf") +/// .source("eos") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _shelf: String, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Bookshelf)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("shelf", self._shelf.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["alt", "shelf", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves/{shelf}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{shelf}", "shelf")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["shelf"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *shelf* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of bookshelf to retrieve. + pub fn shelf(mut self, new_value: &str) -> MylibraryBookshelveGetCall<'a, C, NC, A> { + self._shelf = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of bookshelves belonging to the authenticated user. +/// +/// A builder for the *bookshelves.list* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().bookshelves_list() +/// .source("justo") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryBookshelveListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _source: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryBookshelveListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryBookshelveListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Bookshelves)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.bookshelves.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + for &field in ["alt", "source"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/bookshelves".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryBookshelveListCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryBookshelveListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryBookshelveListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryBookshelveListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves my reading position information for a volume. +/// +/// A builder for the *readingpositions.get* method supported by a *mylibrary* resource. +/// It is not used directly, but through a `MylibraryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mylibrary().readingpositions_get("volumeId") +/// .source("gubergren") +/// .content_version("dolore") +/// .doit(); +/// # } +/// ``` +pub struct MylibraryReadingpositionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _source: Option, + _content_version: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MylibraryReadingpositionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MylibraryReadingpositionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ReadingPosition)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.mylibrary.readingpositions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + if let Some(value) = self._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._content_version { + params.push(("contentVersion", value.to_string())); + } + for &field in ["alt", "volumeId", "source", "contentVersion"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/mylibrary/readingpositions/{volumeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{volumeId}", "volumeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["volumeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of volume for which to retrieve a reading position. + pub fn volume_id(mut self, new_value: &str) -> MylibraryReadingpositionGetCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *source* query property to the given value. + /// + /// + /// String to identify the originator of this request. + pub fn source(mut self, new_value: &str) -> MylibraryReadingpositionGetCall<'a, C, NC, A> { + self._source = Some(new_value.to_string()); + self + } + /// Sets the *content version* query property to the given value. + /// + /// + /// Volume content version for which this reading position is requested. + pub fn content_version(mut self, new_value: &str) -> MylibraryReadingpositionGetCall<'a, C, NC, A> { + self._content_version = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MylibraryReadingpositionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MylibraryReadingpositionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MylibraryReadingpositionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// +/// +/// A builder for the *addBook* method supported by a *cloudloading* resource. +/// It is not used directly, but through a `CloudloadingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cloudloading().add_book() +/// .upload_client_token("amet.") +/// .name("dolore") +/// .mime_type("magna") +/// .drive_document_id("elitr") +/// .doit(); +/// # } +/// ``` +pub struct CloudloadingAddBookCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _upload_client_token: Option, + _name: Option, + _mime_type: Option, + _drive_document_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CloudloadingAddBookCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CloudloadingAddBookCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BooksCloudloadingResource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.cloudloading.addBook", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if let Some(value) = self._upload_client_token { + params.push(("upload_client_token", value.to_string())); + } + if let Some(value) = self._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._mime_type { + params.push(("mime_type", value.to_string())); + } + if let Some(value) = self._drive_document_id { + params.push(("drive_document_id", value.to_string())); + } + for &field in ["alt", "upload_client_token", "name", "mime_type", "drive_document_id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/cloudloading/addBook".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *upload_client_token* query property to the given value. + /// + /// + pub fn upload_client_token(mut self, new_value: &str) -> CloudloadingAddBookCall<'a, C, NC, A> { + self._upload_client_token = Some(new_value.to_string()); + self + } + /// Sets the *name* query property to the given value. + /// + /// + /// The document name. It can be set only if the drive_document_id is set. + pub fn name(mut self, new_value: &str) -> CloudloadingAddBookCall<'a, C, NC, A> { + self._name = Some(new_value.to_string()); + self + } + /// Sets the *mime_type* query property to the given value. + /// + /// + /// The document MIME type. It can be set only if the drive_document_id is set. + pub fn mime_type(mut self, new_value: &str) -> CloudloadingAddBookCall<'a, C, NC, A> { + self._mime_type = Some(new_value.to_string()); + self + } + /// Sets the *drive_document_id* query property to the given value. + /// + /// + /// A drive document id. The upload_client_token must not be set. + pub fn drive_document_id(mut self, new_value: &str) -> CloudloadingAddBookCall<'a, C, NC, A> { + self._drive_document_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CloudloadingAddBookCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CloudloadingAddBookCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CloudloadingAddBookCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// +/// +/// A builder for the *updateBook* method supported by a *cloudloading* resource. +/// It is not used directly, but through a `CloudloadingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// use books1::BooksCloudloadingResource; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: BooksCloudloadingResource = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cloudloading().update_book(&req) +/// .doit(); +/// # } +/// ``` +pub struct CloudloadingUpdateBookCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _request: BooksCloudloadingResource, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CloudloadingUpdateBookCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CloudloadingUpdateBookCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BooksCloudloadingResource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.cloudloading.updateBook", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/books/v1/cloudloading/updateBook".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &BooksCloudloadingResource) -> CloudloadingUpdateBookCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CloudloadingUpdateBookCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CloudloadingUpdateBookCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CloudloadingUpdateBookCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Remove the book and its contents +/// +/// A builder for the *deleteBook* method supported by a *cloudloading* resource. +/// It is not used directly, but through a `CloudloadingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-books1" as books1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use books1::Books; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Books::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cloudloading().delete_book("volumeId") +/// .doit(); +/// # } +/// ``` +pub struct CloudloadingDeleteBookCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Books, + _volume_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CloudloadingDeleteBookCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CloudloadingDeleteBookCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "books.cloudloading.deleteBook", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("volumeId", self._volume_id.to_string())); + for &field in ["volumeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/books/v1/cloudloading/deleteBook".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *volume id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The id of the book to be removed. + pub fn volume_id(mut self, new_value: &str) -> CloudloadingDeleteBookCall<'a, C, NC, A> { + self._volume_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CloudloadingDeleteBookCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CloudloadingDeleteBookCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CloudloadingDeleteBookCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/calendar3/Cargo.toml b/gen/calendar3/Cargo.toml new file mode 100644 index 0000000000..84ceaee59b --- /dev/null +++ b/gen/calendar3/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-calendar3" +version = "0.1.0+20141123" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with calendar (protocol v3)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/calendar3" +homepage = "https://developers.google.com/google-apps/calendar/firstapp" +documentation = "http://byron.github.io/google-apis-rs/google-calendar3" +license = "MIT" +keywords = ["calendar", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/calendar3/LICENSE.md b/gen/calendar3/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/calendar3/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/calendar3/README.md b/gen/calendar3/README.md new file mode 100644 index 0000000000..c80874c4e5 --- /dev/null +++ b/gen/calendar3/README.md @@ -0,0 +1,222 @@ + +The `google-calendar3` library allows access to all features of the *Google calendar* service. + +This documentation was generated from *calendar* crate version *0.1.0+20141123*, where *20141123* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *calendar* *v3* API can be found at the +[official documentation site](https://developers.google.com/google-apps/calendar/firstapp). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarHub.html) ... + +* [acl](http://byron.github.io/google-apis-rs/google-calendar3/struct.Acl.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclPatchCall.html), [*update*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclUpdateCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclWatchCall.html) +* [calendar list](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarList.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListPatchCall.html), [*update*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListUpdateCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListWatchCall.html) +* [calendars](http://byron.github.io/google-apis-rs/google-calendar3/struct.Calendar.html) + * [*clear*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarClearCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarInsertCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarUpdateCall.html) +* [channels](http://byron.github.io/google-apis-rs/google-calendar3/struct.Channel.html) + * [*stop*](http://byron.github.io/google-apis-rs/google-calendar3/struct.ChannelStopCall.html) +* colors + * [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.ColorGetCall.html) +* [events](http://byron.github.io/google-apis-rs/google-calendar3/struct.Event.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventGetCall.html), [*import*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventImportCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventInsertCall.html), [*instances*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventInstanceCall.html), [*list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventListCall.html), [*move*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventMoveCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventPatchCall.html), [*quick add*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventQuickAddCall.html), [*update*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventUpdateCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventWatchCall.html) +* freebusy + * [*query*](http://byron.github.io/google-apis-rs/google-calendar3/struct.FreebusyQueryCall.html) +* [settings](http://byron.github.io/google-apis-rs/google-calendar3/struct.Setting.html) + * [*get*](http://byron.github.io/google-apis-rs/google-calendar3/struct.SettingGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.SettingListCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-calendar3/struct.SettingWatchCall.html) + + +Subscription supported by ... + +* [*list settings*](http://byron.github.io/google-apis-rs/google-calendar3/struct.SettingListCall.html) +* [*list events*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventListCall.html) +* [*list calendar list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListListCall.html) +* [*watch events*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventWatchCall.html) +* [*instances events*](http://byron.github.io/google-apis-rs/google-calendar3/struct.EventInstanceCall.html) +* [*watch settings*](http://byron.github.io/google-apis-rs/google-calendar3/struct.SettingWatchCall.html) +* [*watch acl*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclWatchCall.html) +* [*list acl*](http://byron.github.io/google-apis-rs/google-calendar3/struct.AclListCall.html) +* [*watch calendar list*](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarListWatchCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-calendar3/struct.CalendarHub.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-calendar3/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-calendar3/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-calendar3/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.events().delete(...).doit() +let r = hub.events().insert(...).doit() +let r = hub.events().instances(...).doit() +let r = hub.events().quick_add(...).doit() +let r = hub.events().patch(...).doit() +let r = hub.events().import(...).doit() +let r = hub.events().move_(...).doit() +let r = hub.events().update(...).doit() +let r = hub.events().watch(...).doit() +let r = hub.events().get(...).doit() +let r = hub.events().list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-calendar3 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-calendar3" as calendar3; +use calendar3::Channel; +use calendar3::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use calendar3::CalendarHub; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = CalendarHub::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Channel = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.events().watch(&req, "calendarId") + .updated_min("sit") + .time_zone("Stet") + .time_min("sed") + .time_max("et") + .sync_token("dolores") + .single_events(false) + .show_hidden_invitations(true) + .show_deleted(true) + .add_shared_extended_property("justo") + .q("amet.") + .add_private_extended_property("erat") + .page_token("labore") + .order_by("sea") + .max_results(-90) + .max_attendees(-19) + .i_cal_uid("gubergren") + .always_include_email(false) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-calendar3/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-calendar3/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-calendar3/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-calendar3/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-calendar3/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-calendar3/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-calendar3/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-calendar3/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-calendar3/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-calendar3/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-calendar3/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-calendar3/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-calendar3/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **calendar3** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/calendar3/src/cmn.rs b/gen/calendar3/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/calendar3/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/calendar3/src/lib.rs b/gen/calendar3/src/lib.rs new file mode 100644 index 0000000000..b9efde3b3f --- /dev/null +++ b/gen/calendar3/src/lib.rs @@ -0,0 +1,12234 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *calendar* crate version *0.1.0+20141123*, where *20141123* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *calendar* *v3* API can be found at the +//! [official documentation site](https://developers.google.com/google-apps/calendar/firstapp). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/calendar3). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.CalendarHub.html) ... +//! +//! * [acl](struct.Acl.html) +//! * [*delete*](struct.AclDeleteCall.html), [*get*](struct.AclGetCall.html), [*insert*](struct.AclInsertCall.html), [*list*](struct.AclListCall.html), [*patch*](struct.AclPatchCall.html), [*update*](struct.AclUpdateCall.html) and [*watch*](struct.AclWatchCall.html) +//! * [calendar list](struct.CalendarList.html) +//! * [*delete*](struct.CalendarListDeleteCall.html), [*get*](struct.CalendarListGetCall.html), [*insert*](struct.CalendarListInsertCall.html), [*list*](struct.CalendarListListCall.html), [*patch*](struct.CalendarListPatchCall.html), [*update*](struct.CalendarListUpdateCall.html) and [*watch*](struct.CalendarListWatchCall.html) +//! * [calendars](struct.Calendar.html) +//! * [*clear*](struct.CalendarClearCall.html), [*delete*](struct.CalendarDeleteCall.html), [*get*](struct.CalendarGetCall.html), [*insert*](struct.CalendarInsertCall.html), [*patch*](struct.CalendarPatchCall.html) and [*update*](struct.CalendarUpdateCall.html) +//! * [channels](struct.Channel.html) +//! * [*stop*](struct.ChannelStopCall.html) +//! * colors +//! * [*get*](struct.ColorGetCall.html) +//! * [events](struct.Event.html) +//! * [*delete*](struct.EventDeleteCall.html), [*get*](struct.EventGetCall.html), [*import*](struct.EventImportCall.html), [*insert*](struct.EventInsertCall.html), [*instances*](struct.EventInstanceCall.html), [*list*](struct.EventListCall.html), [*move*](struct.EventMoveCall.html), [*patch*](struct.EventPatchCall.html), [*quick add*](struct.EventQuickAddCall.html), [*update*](struct.EventUpdateCall.html) and [*watch*](struct.EventWatchCall.html) +//! * freebusy +//! * [*query*](struct.FreebusyQueryCall.html) +//! * [settings](struct.Setting.html) +//! * [*get*](struct.SettingGetCall.html), [*list*](struct.SettingListCall.html) and [*watch*](struct.SettingWatchCall.html) +//! +//! +//! Subscription supported by ... +//! +//! * [*list settings*](struct.SettingListCall.html) +//! * [*list events*](struct.EventListCall.html) +//! * [*list calendar list*](struct.CalendarListListCall.html) +//! * [*watch events*](struct.EventWatchCall.html) +//! * [*instances events*](struct.EventInstanceCall.html) +//! * [*watch settings*](struct.SettingWatchCall.html) +//! * [*watch acl*](struct.AclWatchCall.html) +//! * [*list acl*](struct.AclListCall.html) +//! * [*watch calendar list*](struct.CalendarListWatchCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.CalendarHub.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.events().delete(...).doit() +//! let r = hub.events().insert(...).doit() +//! let r = hub.events().instances(...).doit() +//! let r = hub.events().quick_add(...).doit() +//! let r = hub.events().patch(...).doit() +//! let r = hub.events().import(...).doit() +//! let r = hub.events().move_(...).doit() +//! let r = hub.events().update(...).doit() +//! let r = hub.events().watch(...).doit() +//! let r = hub.events().get(...).doit() +//! let r = hub.events().list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-calendar3 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-calendar3" as calendar3; +//! use calendar3::Channel; +//! use calendar3::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use calendar3::CalendarHub; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = CalendarHub::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Channel = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.events().watch(&req, "calendarId") +//! .updated_min("ea") +//! .time_zone("no") +//! .time_min("justo") +//! .time_max("justo") +//! .sync_token("et") +//! .single_events(true) +//! .show_hidden_invitations(true) +//! .show_deleted(false) +//! .add_shared_extended_property("Lorem") +//! .q("et") +//! .add_private_extended_property("duo") +//! .page_token("aliquyam") +//! .order_by("sea") +//! .max_results(-55) +//! .max_attendees(-75) +//! .i_cal_uid("erat") +//! .always_include_email(false) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your calendars + Readonly, + + /// Manage your calendars + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Readonly => "https://www.googleapis.com/auth/calendar.readonly", + Scope::Full => "https://www.googleapis.com/auth/calendar", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all CalendarHub related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// use calendar3::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().watch(&req, "calendarId") +/// .updated_min("eirmod") +/// .time_zone("elitr") +/// .time_min("amet") +/// .time_max("no") +/// .sync_token("labore") +/// .single_events(true) +/// .show_hidden_invitations(true) +/// .show_deleted(true) +/// .add_shared_extended_property("aliquyam") +/// .q("accusam") +/// .add_private_extended_property("Lorem") +/// .page_token("sea") +/// .order_by("et") +/// .max_results(-70) +/// .max_attendees(-21) +/// .i_cal_uid("eirmod") +/// .always_include_email(false) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct CalendarHub { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for CalendarHub {} + +impl<'a, C, NC, A> CalendarHub + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> CalendarHub { + CalendarHub { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn acl(&'a self) -> AclMethods<'a, C, NC, A> { + AclMethods { hub: &self } + } + pub fn calendar_list(&'a self) -> CalendarListMethods<'a, C, NC, A> { + CalendarListMethods { hub: &self } + } + pub fn calendars(&'a self) -> CalendarMethods<'a, C, NC, A> { + CalendarMethods { hub: &self } + } + pub fn channels(&'a self) -> ChannelMethods<'a, C, NC, A> { + ChannelMethods { hub: &self } + } + pub fn colors(&'a self) -> ColorMethods<'a, C, NC, A> { + ColorMethods { hub: &self } + } + pub fn events(&'a self) -> EventMethods<'a, C, NC, A> { + EventMethods { hub: &self } + } + pub fn freebusy(&'a self) -> FreebusyMethods<'a, C, NC, A> { + FreebusyMethods { hub: &self } + } + pub fn settings(&'a self) -> SettingMethods<'a, C, NC, A> { + SettingMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A gadget that extends this event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventGadget { + /// Preferences. + pub preferences: HashMap, + /// The gadget's title. + pub title: String, + /// The gadget's height in pixels. Optional. + pub height: i32, + /// The gadget's width in pixels. Optional. + pub width: i32, + /// The gadget's URL. + pub link: String, + /// The gadget's type. + #[serde(alias="type")] + pub type_: String, + /// The gadget's display mode. Optional. Possible values are: + /// - "icon" - The gadget displays next to the event's title in the calendar view. + /// - "chip" - The gadget displays when the event is clicked. + pub display: String, + /// The gadget's icon URL. + #[serde(alias="iconLink")] + pub icon_link: String, +} + +impl NestedType for EventGadget {} +impl Part for EventGadget {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FreeBusyCalendar { + /// List of time ranges during which this calendar should be regarded as busy. + pub busy: Vec, + /// Optional error(s) (if computation for the calendar failed). + pub errors: Vec, +} + +impl Part for FreeBusyCalendar {} + + +/// The scope of the rule. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AclRuleScope { + /// The type of the scope. Possible values are: + /// - "default" - The public scope. This is the default value. + /// - "user" - Limits the scope to a single user. + /// - "group" - Limits the scope to a group. + /// - "domain" - Limits the scope to a domain. Note: The permissions granted to the "default", or public, scope apply to any user, authenticated or not. + #[serde(alias="type")] + pub type_: String, + /// The email address of a user or group, or the name of a domain, depending on the scope type. Omitted for type "default". + pub value: String, +} + +impl NestedType for AclRuleScope {} +impl Part for AclRuleScope {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list settings](struct.SettingListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Settings { + /// Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of user settings. + pub items: Vec, + /// Type of the collection ("calendar#settings"). + pub kind: String, + /// Etag of the collection. + pub etag: String, + /// Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are available, in which case nextPageToken is provided. + #[serde(alias="nextSyncToken")] + pub next_sync_token: String, +} + +impl ResponseResult for Settings {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [clear calendars](struct.CalendarClearCall.html) (none) +/// * [get calendars](struct.CalendarGetCall.html) (response) +/// * [update calendars](struct.CalendarUpdateCall.html) (request|response) +/// * [patch calendars](struct.CalendarPatchCall.html) (request|response) +/// * [insert calendars](struct.CalendarInsertCall.html) (request|response) +/// * [delete calendars](struct.CalendarDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Calendar { + /// Type of the resource ("calendar#calendar"). + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Description of the calendar. Optional. + pub description: Option, + /// Identifier of the calendar. + pub id: Option, + /// The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) Optional. + #[serde(alias="timeZone")] + pub time_zone: Option, + /// Geographic location of the calendar as free-form text. Optional. + pub location: Option, + /// Title of the calendar. + pub summary: Option, +} + +impl RequestValue for Calendar {} +impl Resource for Calendar {} +impl ResponseResult for Calendar {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get calendar list](struct.CalendarListGetCall.html) (response) +/// * [update calendar list](struct.CalendarListUpdateCall.html) (request|response) +/// * [patch calendar list](struct.CalendarListPatchCall.html) (request|response) +/// * [insert calendar list](struct.CalendarListInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CalendarListEntry { + /// The notifications that the authenticated user is receiving for this calendar. + #[serde(alias="notificationSettings")] + pub notification_settings: Option, + /// Description of the calendar. Optional. Read-only. + pub description: Option, + /// Whether this calendar list entry has been deleted from the calendar list. Read-only. Optional. The default is False. + pub deleted: Option, + /// Whether the calendar is the primary calendar of the authenticated user. Read-only. Optional. The default is False. + pub primary: Option, + /// The effective access role that the authenticated user has on the calendar. Read-only. Possible values are: + /// - "freeBusyReader" - Provides read access to free/busy information. + /// - "reader" - Provides read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. + /// - "writer" - Provides read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. + /// - "owner" - Provides ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs. + #[serde(alias="accessRole")] + pub access_role: Option, + /// Identifier of the calendar. + pub id: Option, + /// Type of the resource ("calendar#calendarListEntry"). + pub kind: Option, + /// The foreground color of the calendar in the hexadecimal format "#ffffff". This property supersedes the index-based colorId property. Optional. + #[serde(alias="foregroundColor")] + pub foreground_color: Option, + /// The default reminders that the authenticated user has for this calendar. + #[serde(alias="defaultReminders")] + pub default_reminders: Option>, + /// The color of the calendar. This is an ID referring to an entry in the calendar section of the colors definition (see the colors endpoint). Optional. + #[serde(alias="colorId")] + pub color_id: Option, + /// Whether the calendar content shows up in the calendar UI. Optional. The default is False. + pub selected: Option, + /// Title of the calendar. Read-only. + pub summary: Option, + /// ETag of the resource. + pub etag: Option, + /// Geographic location of the calendar as free-form text. Optional. Read-only. + pub location: Option, + /// The main color of the calendar in the hexadecimal format "#0088aa". This property supersedes the index-based colorId property. Optional. + #[serde(alias="backgroundColor")] + pub background_color: Option, + /// The summary that the authenticated user has set for this calendar. Optional. + #[serde(alias="summaryOverride")] + pub summary_override: Option, + /// The time zone of the calendar. Optional. Read-only. + #[serde(alias="timeZone")] + pub time_zone: Option, + /// Whether the calendar has been hidden from the list. Optional. The default is False. + pub hidden: Option, +} + +impl RequestValue for CalendarListEntry {} +impl ResponseResult for CalendarListEntry {} + + +/// The notifications that the authenticated user is receiving for this calendar. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CalendarListEntryNotificationSettings { + /// The list of notifications set for this calendar. + pub notifications: Vec, +} + +impl NestedType for CalendarListEntryNotificationSettings {} +impl Part for CalendarListEntryNotificationSettings {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ColorDefinition { + /// The foreground color that can be used to write on top of a background with 'background' color. + pub foreground: String, + /// The background color associated with this color definition. + pub background: String, +} + +impl Part for ColorDefinition {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventDateTime { + /// The date, in the format "yyyy-mm-dd", if this is an all-day event. + pub date: String, + /// The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) For recurring events this field is required and specifies the time zone in which the recurrence is expanded. For single events this field is optional and indicates a custom time zone for the event start/end. + #[serde(alias="timeZone")] + pub time_zone: String, + /// The time, as a combined date-time value (formatted according to RFC 3339). A time zone offset is required unless a time zone is explicitly specified in timeZone. + #[serde(alias="dateTime")] + pub date_time: String, +} + +impl Part for EventDateTime {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list settings](struct.SettingListCall.html) (none) +/// * [watch settings](struct.SettingWatchCall.html) (none) +/// * [get settings](struct.SettingGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Setting { + /// Type of the resource ("calendar#setting"). + pub kind: String, + /// ETag of the resource. + pub etag: String, + /// The id of the user setting. + pub id: String, + /// Value of the user setting. The format of the value depends on the ID of the setting. It must always be a UTF-8 string of length up to 1024 characters. + pub value: String, +} + +impl Resource for Setting {} +impl ResponseResult for Setting {} + + +/// The creator of the event. Read-only. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventCreator { + /// Whether the creator corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. + #[serde(alias="self")] + pub self_: bool, + /// The creator's name, if available. + #[serde(alias="displayName")] + pub display_name: String, + /// The creator's email address, if available. + pub email: String, + /// The creator's Profile ID, if available. + pub id: String, +} + +impl NestedType for EventCreator {} +impl Part for EventCreator {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Error { + /// Domain, or broad category, of the error. + pub domain: String, + /// Specific reason for the error. Some of the possible values are: + /// - "groupTooBig" - The group of users requested is too large for a single query. + /// - "tooManyCalendarsRequested" - The number of calendars requested is too large for a single query. + /// - "notFound" - The requested resource was not found. + /// - "internalError" - The API service has encountered an internal error. Additional error types may be added in the future, so clients should gracefully handle additional error statuses not included in this list. + pub reason: String, +} + +impl Part for Error {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch acl](struct.AclPatchCall.html) (request|response) +/// * [update acl](struct.AclUpdateCall.html) (request|response) +/// * [get acl](struct.AclGetCall.html) (response) +/// * [insert acl](struct.AclInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AclRule { + /// The scope of the rule. + pub scope: Option, + /// Type of the resource ("calendar#aclRule"). + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// The role assigned to the scope. Possible values are: + /// - "none" - Provides no access. + /// - "freeBusyReader" - Provides read access to free/busy information. + /// - "reader" - Provides read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. + /// - "writer" - Provides read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. + /// - "owner" - Provides ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs. + pub role: Option, + /// Identifier of the ACL rule. + pub id: Option, +} + +impl RequestValue for AclRule {} +impl ResponseResult for AclRule {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list acl](struct.AclListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Acl { + /// Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of rules on the access control list. + pub items: Vec, + /// Type of the collection ("calendar#acl"). + pub kind: String, + /// ETag of the collection. + pub etag: String, + /// Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are available, in which case nextPageToken is provided. + #[serde(alias="nextSyncToken")] + pub next_sync_token: String, +} + +impl ResponseResult for Acl {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [instances events](struct.EventInstanceCall.html) (response) +/// * [list events](struct.EventListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Events { + /// Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Type of the collection ("calendar#events"). + pub kind: String, + /// The default reminders on the calendar for the authenticated user. These reminders apply to all events on this calendar that do not explicitly override them (i.e. do not have reminders.useDefault set to True). + #[serde(alias="defaultReminders")] + pub default_reminders: Vec, + /// Description of the calendar. Read-only. + pub description: String, + /// List of events on the calendar. + pub items: Vec, + /// Last modification time of the calendar (as a RFC 3339 timestamp). Read-only. + pub updated: String, + /// Title of the calendar. Read-only. + pub summary: String, + /// ETag of the collection. + pub etag: String, + /// Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are available, in which case nextPageToken is provided. + #[serde(alias="nextSyncToken")] + pub next_sync_token: String, + /// The time zone of the calendar. Read-only. + #[serde(alias="timeZone")] + pub time_zone: String, + /// The user's access role for this calendar. Read-only. Possible values are: + /// - "none" - The user has no access. + /// - "freeBusyReader" - The user has read access to free/busy information. + /// - "reader" - The user has read access to the calendar. Private events will appear to users with reader access, but event details will be hidden. + /// - "writer" - The user has read and write access to the calendar. Private events will appear to users with writer access, and event details will be visible. + /// - "owner" - The user has ownership of the calendar. This role has all of the permissions of the writer role with the additional ability to see and manipulate ACLs. + #[serde(alias="accessRole")] + pub access_role: String, +} + +impl ResponseResult for Events {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [stop channels](struct.ChannelStopCall.html) (request) +/// * [watch settings](struct.SettingWatchCall.html) (request|response) +/// * [watch acl](struct.AclWatchCall.html) (request|response) +/// * [watch calendar list](struct.CalendarListWatchCall.html) (request|response) +/// * [watch events](struct.EventWatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Channel { + /// A version-specific identifier for the watched resource. + #[serde(alias="resourceUri")] + pub resource_uri: Option, + /// Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". + pub kind: Option, + /// An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. + #[serde(alias="resourceId")] + pub resource_id: Option, + /// A UUID or similar unique string that identifies this channel. + pub id: Option, + /// An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. + pub token: Option, + /// Additional parameters controlling delivery channel behavior. Optional. + pub params: Option>, + /// Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. + pub expiration: Option, + /// The address where notifications are delivered for this channel. + pub address: Option, + /// The type of delivery mechanism used for this channel. + #[serde(alias="type")] + pub type_: Option, + /// A Boolean value to indicate whether payload is wanted. Optional. + pub payload: Option, +} + +impl RequestValue for Channel {} +impl Resource for Channel {} +impl ResponseResult for Channel {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventAttendee { + /// The attendee's response comment. Optional. + pub comment: String, + /// The attendee's name, if available. Optional. + #[serde(alias="displayName")] + pub display_name: String, + /// Whether this entry represents the calendar on which this copy of the event appears. Read-only. The default is False. + #[serde(alias="self")] + pub self_: bool, + /// The attendee's email address, if available. This field must be present when adding an attendee. + pub email: String, + /// The attendee's Profile ID, if available. + pub id: String, + /// Number of additional guests. Optional. The default is 0. + #[serde(alias="additionalGuests")] + pub additional_guests: i32, + /// Whether the attendee is a resource. Read-only. The default is False. + pub resource: bool, + /// Whether the attendee is the organizer of the event. Read-only. The default is False. + pub organizer: bool, + /// Whether this is an optional attendee. Optional. The default is False. + pub optional: bool, + /// The attendee's response status. Possible values are: + /// - "needsAction" - The attendee has not responded to the invitation. + /// - "declined" - The attendee has declined the invitation. + /// - "tentative" - The attendee has tentatively accepted the invitation. + /// - "accepted" - The attendee has accepted the invitation. + #[serde(alias="responseStatus")] + pub response_status: String, +} + +impl Part for EventAttendee {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FreeBusyGroup { + /// Optional error(s) (if computation for the group failed). + pub errors: Vec, + /// List of calendars' identifiers within a group. + pub calendars: Vec, +} + +impl Part for FreeBusyGroup {} + + +/// Information about the event's reminders for the authenticated user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventReminders { + /// If the event doesn't use the default reminders, this lists the reminders specific to the event, or, if not set, indicates that no reminders are set for this event. + pub overrides: Vec, + /// Whether the default reminders of the calendar apply to the event. + #[serde(alias="useDefault")] + pub use_default: bool, +} + +impl NestedType for EventReminders {} +impl Part for EventReminders {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list calendar list](struct.CalendarListListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CalendarList { + /// Token used to access the next page of this result. Omitted if no further results are available, in which case nextSyncToken is provided. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Calendars that are present on the user's calendar list. + pub items: Vec, + /// Type of the collection ("calendar#calendarList"). + pub kind: String, + /// ETag of the collection. + pub etag: String, + /// Token used at a later point in time to retrieve only the entries that have changed since this result was returned. Omitted if further results are available, in which case nextPageToken is provided. + #[serde(alias="nextSyncToken")] + pub next_sync_token: String, +} + +impl ResponseResult for CalendarList {} + + +/// Extended properties of the event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventExtendedProperties { + /// Properties that are shared between copies of the event on other attendees' calendars. + pub shared: HashMap, + /// Properties that are private to the copy of the event that appears on this calendar. + pub private: HashMap, +} + +impl NestedType for EventExtendedProperties {} +impl Part for EventExtendedProperties {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct FreeBusyRequestItem { + /// The identifier of a calendar or a group. + pub id: String, +} + +impl Part for FreeBusyRequestItem {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query freebusy](struct.FreebusyQueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FreeBusyResponse { + /// The end of the interval. + #[serde(alias="timeMax")] + pub time_max: String, + /// Type of the resource ("calendar#freeBusy"). + pub kind: String, + /// List of free/busy information for calendars. + pub calendars: HashMap, + /// Expansion of groups. + pub groups: HashMap, + /// The start of the interval. + #[serde(alias="timeMin")] + pub time_min: String, +} + +impl ResponseResult for FreeBusyResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get colors](struct.ColorGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Colors { + /// Palette of calendar colors, mapping from the color ID to its definition. A calendarListEntry resource refers to one of these color IDs in its color field. Read-only. + pub calendar: HashMap, + /// Last modification time of the color palette (as a RFC 3339 timestamp). Read-only. + pub updated: String, + /// Type of the resource ("calendar#colors"). + pub kind: String, + /// Palette of event colors, mapping from the color ID to its definition. An event resource may refer to one of these color IDs in its color field. Read-only. + pub event: HashMap, +} + +impl ResponseResult for Colors {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query freebusy](struct.FreebusyQueryCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct FreeBusyRequest { + /// Maximal number of calendars for which FreeBusy information is to be provided. Optional. + #[serde(alias="calendarExpansionMax")] + pub calendar_expansion_max: Option, + /// The start of the interval for the query. + #[serde(alias="timeMin")] + pub time_min: Option, + /// Maximal number of calendar identifiers to be provided for a single group. Optional. An error will be returned for a group with more members than this value. + #[serde(alias="groupExpansionMax")] + pub group_expansion_max: Option, + /// The end of the interval for the query. + #[serde(alias="timeMax")] + pub time_max: Option, + /// List of calendars and/or groups to query. + pub items: Option>, + /// Time zone used in the response. Optional. The default is UTC. + #[serde(alias="timeZone")] + pub time_zone: Option, +} + +impl RequestValue for FreeBusyRequest {} + + +/// Source of an event from which it was created; for example a web page, an email message or any document identifiable by an URL using HTTP/HTTPS protocol. Accessible only by the creator of the event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventSource { + /// URL of the source pointing to a resource. URL's protocol must be HTTP or HTTPS. + pub url: String, + /// Title of the source; for example a title of a web page or an email subject. + pub title: String, +} + +impl NestedType for EventSource {} +impl Part for EventSource {} + + +/// The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventOrganizer { + /// Whether the organizer corresponds to the calendar on which this copy of the event appears. Read-only. The default is False. + #[serde(alias="self")] + pub self_: bool, + /// The organizer's name, if available. + #[serde(alias="displayName")] + pub display_name: String, + /// The organizer's email address, if available. + pub email: String, + /// The organizer's Profile ID, if available. + pub id: String, +} + +impl NestedType for EventOrganizer {} +impl Part for EventOrganizer {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventReminder { + /// Number of minutes before the start of the event when the reminder should trigger. + pub minutes: i32, + /// The method used by this reminder. Possible values are: + /// - "email" - Reminders are sent via email. + /// - "sms" - Reminders are sent via SMS. + /// - "popup" - Reminders are sent via a UI popup. + pub method: String, +} + +impl Part for EventReminder {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TimePeriod { + /// The (inclusive) start of the time period. + pub start: String, + /// The (exclusive) end of the time period. + pub end: String, +} + +impl Part for TimePeriod {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CalendarNotification { + /// The type of notification. Possible values are: + /// - "eventCreation" - Notification sent when a new event is put on the calendar. + /// - "eventChange" - Notification sent when an event is changed. + /// - "eventCancellation" - Notification sent when an event is cancelled. + /// - "eventResponse" - Notification sent when an event is changed. + /// - "agenda" - An agenda with the events of the day (sent out in the morning). + #[serde(alias="type")] + pub type_: String, + /// The method used to deliver the notification. Possible values are: + /// - "email" - Reminders are sent via email. + /// - "sms" - Reminders are sent via SMS. This value is read-only and is ignored on inserts and updates. + pub method: String, +} + +impl Part for CalendarNotification {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete events](struct.EventDeleteCall.html) (none) +/// * [insert events](struct.EventInsertCall.html) (request|response) +/// * [instances events](struct.EventInstanceCall.html) (none) +/// * [quick add events](struct.EventQuickAddCall.html) (response) +/// * [patch events](struct.EventPatchCall.html) (request|response) +/// * [import events](struct.EventImportCall.html) (request|response) +/// * [move events](struct.EventMoveCall.html) (response) +/// * [update events](struct.EventUpdateCall.html) (request|response) +/// * [watch events](struct.EventWatchCall.html) (none) +/// * [get events](struct.EventGetCall.html) (response) +/// * [list events](struct.EventListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Event { + /// The creator of the event. Read-only. + pub creator: Option, + /// The organizer of the event. If the organizer is also an attendee, this is indicated with a separate entry in attendees with the organizer field set to True. To change the organizer, use the move operation. Read-only, except when importing an event. + pub organizer: Option, + /// Identifier of the event. When creating new single or recurring events, you can specify their IDs. Provided IDs must follow these rules: + /// - characters allowed in the ID are those used in base32hex encoding, i.e. lowercase letters a-v and digits 0-9, see section 3.1.2 in RFC2938 + /// - the length of the ID must be between 5 and 1024 characters + /// - the ID must be unique per calendar Due to the globally distributed nature of the system, we cannot guarantee that ID collisions will be detected at event creation time. To minimize the risk of collisions we recommend using an established UUID algorithm such as one described in RFC4122. + pub id: Option, + /// An absolute link to the Google+ hangout associated with this event. Read-only. + #[serde(alias="hangoutLink")] + pub hangout_link: Option, + /// Whether attendees other than the organizer can invite others to the event. Optional. The default is True. + #[serde(alias="guestsCanInviteOthers")] + pub guests_can_invite_others: Option, + /// The attendees of the event. + pub attendees: Option>, + /// The (inclusive) start time of the event. For a recurring event, this is the start time of the first instance. + pub start: Option, + /// An absolute link to this event in the Google Calendar Web UI. Read-only. + #[serde(alias="htmlLink")] + pub html_link: Option, + /// List of RRULE, EXRULE, RDATE and EXDATE lines for a recurring event. This field is omitted for single events or instances of recurring events. + pub recurrence: Option>, + /// Source of an event from which it was created; for example a web page, an email message or any document identifiable by an URL using HTTP/HTTPS protocol. Accessible only by the creator of the event. + pub source: Option, + /// ETag of the resource. + pub etag: Option, + /// Geographic location of the event as free-form text. Optional. + pub location: Option, + /// For an instance of a recurring event, this is the event ID of the recurring event itself. Immutable. + #[serde(alias="recurringEventId")] + pub recurring_event_id: Option, + /// For an instance of a recurring event, this is the time at which this event would start according to the recurrence data in the recurring event identified by recurringEventId. Immutable. + #[serde(alias="originalStartTime")] + pub original_start_time: Option, + /// Status of the event. Optional. Possible values are: + /// - "confirmed" - The event is confirmed. This is the default status. + /// - "tentative" - The event is tentatively confirmed. + /// - "cancelled" - The event is cancelled. + pub status: Option, + /// Last modification time of the event (as a RFC 3339 timestamp). Read-only. + pub updated: Option, + /// Description of the event. Optional. + pub description: Option, + /// Event ID in the iCalendar format. + #[serde(alias="iCalUID")] + pub i_cal_uid: Option, + /// A gadget that extends this event. + pub gadget: Option, + /// Whether the end time is actually unspecified. An end time is still provided for compatibility reasons, even if this attribute is set to True. The default is False. + #[serde(alias="endTimeUnspecified")] + pub end_time_unspecified: Option, + /// Sequence number as per iCalendar. + pub sequence: Option, + /// Visibility of the event. Optional. Possible values are: + /// - "default" - Uses the default visibility for events on the calendar. This is the default value. + /// - "public" - The event is public and event details are visible to all readers of the calendar. + /// - "private" - The event is private and only event attendees may view event details. + /// - "confidential" - The event is private. This value is provided for compatibility reasons. + pub visibility: Option, + /// Whether attendees other than the organizer can modify the event. Optional. The default is False. + #[serde(alias="guestsCanModify")] + pub guests_can_modify: Option, + /// The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance. + pub end: Option, + /// Whether attendees may have been omitted from the event's representation. When retrieving an event, this may be due to a restriction specified by the maxAttendee query parameter. When updating an event, this can be used to only update the participant's response. Optional. The default is False. + #[serde(alias="attendeesOmitted")] + pub attendees_omitted: Option, + /// Type of the resource ("calendar#event"). + pub kind: Option, + /// Whether this is a locked event copy where no changes can be made to the main event fields "summary", "description", "location", "start", "end" or "recurrence". The default is False. Read-Only. + pub locked: Option, + /// Creation time of the event (as a RFC 3339 timestamp). Read-only. + pub created: Option, + /// The color of the event. This is an ID referring to an entry in the event section of the colors definition (see the colors endpoint). Optional. + #[serde(alias="colorId")] + pub color_id: Option, + /// Whether anyone can invite themselves to the event. Optional. The default is False. + #[serde(alias="anyoneCanAddSelf")] + pub anyone_can_add_self: Option, + /// Information about the event's reminders for the authenticated user. + pub reminders: Option, + /// Whether attendees other than the organizer can see who the event's attendees are. Optional. The default is True. + #[serde(alias="guestsCanSeeOtherGuests")] + pub guests_can_see_other_guests: Option, + /// Title of the event. + pub summary: Option, + /// Extended properties of the event. + #[serde(alias="extendedProperties")] + pub extended_properties: Option, + /// Whether the event blocks time on the calendar. Optional. Possible values are: + /// - "opaque" - The event blocks time on the calendar. This is the default value. + /// - "transparent" - The event does not block time on the calendar. + pub transparency: Option, + /// Whether this is a private event copy where changes are not shared with other copies on other calendars. Optional. Immutable. The default is False. + #[serde(alias="privateCopy")] + pub private_copy: Option, +} + +impl RequestValue for Event {} +impl Resource for Event {} +impl ResponseResult for Event {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *freebusy* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `query(...)` +/// // to build up your call. +/// let rb = hub.freebusy(); +/// # } +/// ``` +pub struct FreebusyMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FreebusyMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FreebusyMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns free/busy information for a set of calendars. + pub fn query(&self, request: &FreeBusyRequest) -> FreebusyQueryCall<'a, C, NC, A> { + FreebusyQueryCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *setting* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.settings(); +/// # } +/// ``` +pub struct SettingMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SettingMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SettingMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns all user settings for the authenticated user. + pub fn list(&self) -> SettingListCall<'a, C, NC, A> { + SettingListCall { + hub: self.hub, + _sync_token: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes to Settings resources. + pub fn watch(&self, request: &Channel) -> SettingWatchCall<'a, C, NC, A> { + SettingWatchCall { + hub: self.hub, + _request: request.clone(), + _sync_token: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a single user setting. + pub fn get(&self, setting: &str) -> SettingGetCall<'a, C, NC, A> { + SettingGetCall { + hub: self.hub, + _setting: setting.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *calendarList* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `update(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.calendar_list(); +/// # } +/// ``` +pub struct CalendarListMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CalendarListMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an entry on the user's calendar list. + pub fn update(&self, request: &CalendarListEntry, calendar_id: &str) -> CalendarListUpdateCall<'a, C, NC, A> { + CalendarListUpdateCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _color_rgb_format: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an entry on the user's calendar list. + pub fn delete(&self, calendar_id: &str) -> CalendarListDeleteCall<'a, C, NC, A> { + CalendarListDeleteCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns an entry on the user's calendar list. + pub fn get(&self, calendar_id: &str) -> CalendarListGetCall<'a, C, NC, A> { + CalendarListGetCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns entries on the user's calendar list. + pub fn list(&self) -> CalendarListListCall<'a, C, NC, A> { + CalendarListListCall { + hub: self.hub, + _sync_token: Default::default(), + _show_hidden: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _min_access_role: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds an entry to the user's calendar list. + pub fn insert(&self, request: &CalendarListEntry) -> CalendarListInsertCall<'a, C, NC, A> { + CalendarListInsertCall { + hub: self.hub, + _request: request.clone(), + _color_rgb_format: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an entry on the user's calendar list. This method supports patch semantics. + pub fn patch(&self, request: &CalendarListEntry, calendar_id: &str) -> CalendarListPatchCall<'a, C, NC, A> { + CalendarListPatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _color_rgb_format: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes to CalendarList resources. + pub fn watch(&self, request: &Channel) -> CalendarListWatchCall<'a, C, NC, A> { + CalendarListWatchCall { + hub: self.hub, + _request: request.clone(), + _sync_token: Default::default(), + _show_hidden: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _min_access_role: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *calendar* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `clear(...)`, `delete(...)`, `get(...)`, `insert(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.calendars(); +/// # } +/// ``` +pub struct CalendarMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CalendarMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates metadata for a calendar. This method supports patch semantics. + pub fn patch(&self, request: &Calendar, calendar_id: &str) -> CalendarPatchCall<'a, C, NC, A> { + CalendarPatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a secondary calendar. Use calendars.clear for clearing all events on primary calendars. + pub fn delete(&self, calendar_id: &str) -> CalendarDeleteCall<'a, C, NC, A> { + CalendarDeleteCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns metadata for a calendar. + pub fn get(&self, calendar_id: &str) -> CalendarGetCall<'a, C, NC, A> { + CalendarGetCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Clears a primary calendar. This operation deletes all events associated with the primary calendar of an account. + pub fn clear(&self, calendar_id: &str) -> CalendarClearCall<'a, C, NC, A> { + CalendarClearCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a secondary calendar. + pub fn insert(&self, request: &Calendar) -> CalendarInsertCall<'a, C, NC, A> { + CalendarInsertCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates metadata for a calendar. + pub fn update(&self, request: &Calendar, calendar_id: &str) -> CalendarUpdateCall<'a, C, NC, A> { + CalendarUpdateCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *acl* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `update(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.acl(); +/// # } +/// ``` +pub struct AclMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AclMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes to ACL resources. + pub fn watch(&self, request: &Channel, calendar_id: &str) -> AclWatchCall<'a, C, NC, A> { + AclWatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _sync_token: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an access control rule. + pub fn insert(&self, request: &AclRule, calendar_id: &str) -> AclInsertCall<'a, C, NC, A> { + AclInsertCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an access control rule. + pub fn update(&self, request: &AclRule, calendar_id: &str, rule_id: &str) -> AclUpdateCall<'a, C, NC, A> { + AclUpdateCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _rule_id: rule_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an access control rule. This method supports patch semantics. + pub fn patch(&self, request: &AclRule, calendar_id: &str, rule_id: &str) -> AclPatchCall<'a, C, NC, A> { + AclPatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _rule_id: rule_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the rules in the access control list for the calendar. + pub fn list(&self, calendar_id: &str) -> AclListCall<'a, C, NC, A> { + AclListCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _sync_token: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an access control rule. + pub fn delete(&self, calendar_id: &str, rule_id: &str) -> AclDeleteCall<'a, C, NC, A> { + AclDeleteCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _rule_id: rule_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns an access control rule. + pub fn get(&self, calendar_id: &str, rule_id: &str) -> AclGetCall<'a, C, NC, A> { + AclGetCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _rule_id: rule_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *channel* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `stop(...)` +/// // to build up your call. +/// let rb = hub.channels(); +/// # } +/// ``` +pub struct ChannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Stop watching resources through this channel + pub fn stop(&self, request: &Channel) -> ChannelStopCall<'a, C, NC, A> { + ChannelStopCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *color* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.colors(); +/// # } +/// ``` +pub struct ColorMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ColorMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ColorMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the color definitions for calendars and events. + pub fn get(&self) -> ColorGetCall<'a, C, NC, A> { + ColorGetCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *event* resources. +/// It is not used directly, but through the `CalendarHub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-calendar3" as calendar3; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use calendar3::CalendarHub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `import(...)`, `insert(...)`, `instances(...)`, `list(...)`, `move_(...)`, `patch(...)`, `quick_add(...)`, `update(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.events(); +/// # } +/// ``` +pub struct EventMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for EventMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an event. + pub fn delete(&self, calendar_id: &str, event_id: &str) -> EventDeleteCall<'a, C, NC, A> { + EventDeleteCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _send_notifications: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an event. + pub fn insert(&self, request: &Event, calendar_id: &str) -> EventInsertCall<'a, C, NC, A> { + EventInsertCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _send_notifications: Default::default(), + _max_attendees: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Imports an event. This operation is used to add a private copy of an existing event to a calendar. + pub fn import(&self, request: &Event, calendar_id: &str) -> EventImportCall<'a, C, NC, A> { + EventImportCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns instances of the specified recurring event. + pub fn instances(&self, calendar_id: &str, event_id: &str) -> EventInstanceCall<'a, C, NC, A> { + EventInstanceCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _time_zone: Default::default(), + _time_min: Default::default(), + _time_max: Default::default(), + _show_deleted: Default::default(), + _page_token: Default::default(), + _original_start: Default::default(), + _max_results: Default::default(), + _max_attendees: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns an event. + pub fn get(&self, calendar_id: &str, event_id: &str) -> EventGetCall<'a, C, NC, A> { + EventGetCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _time_zone: Default::default(), + _max_attendees: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns events on the specified calendar. + pub fn list(&self, calendar_id: &str) -> EventListCall<'a, C, NC, A> { + EventListCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _updated_min: Default::default(), + _time_zone: Default::default(), + _time_min: Default::default(), + _time_max: Default::default(), + _sync_token: Default::default(), + _single_events: Default::default(), + _show_hidden_invitations: Default::default(), + _show_deleted: Default::default(), + _shared_extended_property: Default::default(), + _q: Default::default(), + _private_extended_property: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _max_attendees: Default::default(), + _i_cal_uid: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an event. This method supports patch semantics. + pub fn patch(&self, request: &Event, calendar_id: &str, event_id: &str) -> EventPatchCall<'a, C, NC, A> { + EventPatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _send_notifications: Default::default(), + _max_attendees: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Moves an event to another calendar, i.e. changes an event's organizer. + pub fn move_(&self, calendar_id: &str, event_id: &str, destination: &str) -> EventMoveCall<'a, C, NC, A> { + EventMoveCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _destination: destination.to_string(), + _send_notifications: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an event. + pub fn update(&self, request: &Event, calendar_id: &str, event_id: &str) -> EventUpdateCall<'a, C, NC, A> { + EventUpdateCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _event_id: event_id.to_string(), + _send_notifications: Default::default(), + _max_attendees: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Watch for changes to Events resources. + pub fn watch(&self, request: &Channel, calendar_id: &str) -> EventWatchCall<'a, C, NC, A> { + EventWatchCall { + hub: self.hub, + _request: request.clone(), + _calendar_id: calendar_id.to_string(), + _updated_min: Default::default(), + _time_zone: Default::default(), + _time_min: Default::default(), + _time_max: Default::default(), + _sync_token: Default::default(), + _single_events: Default::default(), + _show_hidden_invitations: Default::default(), + _show_deleted: Default::default(), + _shared_extended_property: Default::default(), + _q: Default::default(), + _private_extended_property: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _max_attendees: Default::default(), + _i_cal_uid: Default::default(), + _always_include_email: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an event based on a simple text string. + pub fn quick_add(&self, calendar_id: &str, text: &str) -> EventQuickAddCall<'a, C, NC, A> { + EventQuickAddCall { + hub: self.hub, + _calendar_id: calendar_id.to_string(), + _text: text.to_string(), + _send_notifications: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns free/busy information for a set of calendars. +/// +/// A builder for the *query* method supported by a *freebusy* resource. +/// It is not used directly, but through a `FreebusyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::FreeBusyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FreeBusyRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.freebusy().query(&req) +/// .doit(); +/// # } +/// ``` +pub struct FreebusyQueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: FreeBusyRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FreebusyQueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FreebusyQueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FreeBusyResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.freebusy.query", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/freeBusy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FreeBusyRequest) -> FreebusyQueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FreebusyQueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FreebusyQueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FreebusyQueryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns all user settings for the authenticated user. +/// +/// A builder for the *list* method supported by a *setting* resource. +/// It is not used directly, but through a `SettingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.settings().list() +/// .sync_token("et") +/// .page_token("amet") +/// .max_results(-23) +/// .doit(); +/// # } +/// ``` +pub struct SettingListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _sync_token: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SettingListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SettingListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Settings)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.settings.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "syncToken", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/settings".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> SettingListCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> SettingListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> SettingListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SettingListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SettingListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SettingListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes to Settings resources. +/// +/// A builder for the *watch* method supported by a *setting* resource. +/// It is not used directly, but through a `SettingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.settings().watch(&req) +/// .sync_token("consetetur") +/// .page_token("ut") +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct SettingWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Channel, + _sync_token: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SettingWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SettingWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.settings.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "syncToken", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/settings/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> SettingWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> SettingWatchCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> SettingWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> SettingWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SettingWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SettingWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SettingWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a single user setting. +/// +/// A builder for the *get* method supported by a *setting* resource. +/// It is not used directly, but through a `SettingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.settings().get("setting") +/// .doit(); +/// # } +/// ``` +pub struct SettingGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _setting: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SettingGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SettingGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Setting)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.settings.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("setting", self._setting.to_string())); + for &field in ["alt", "setting"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/settings/{setting}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{setting}", "setting")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["setting"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *setting* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The id of the user setting. + pub fn setting(mut self, new_value: &str) -> SettingGetCall<'a, C, NC, A> { + self._setting = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SettingGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SettingGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SettingGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an entry on the user's calendar list. +/// +/// A builder for the *update* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::CalendarListEntry; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CalendarListEntry = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().update(&req, "calendarId") +/// .color_rgb_format(true) +/// .doit(); +/// # } +/// ``` +pub struct CalendarListUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: CalendarListEntry, + _calendar_id: String, + _color_rgb_format: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CalendarListEntry)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._color_rgb_format { + params.push(("colorRgbFormat", value.to_string())); + } + for &field in ["alt", "calendarId", "colorRgbFormat"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CalendarListEntry) -> CalendarListUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarListUpdateCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *color rgb format* query property to the given value. + /// + /// + /// Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId field will be set to the best matching option automatically. Optional. The default is False. + pub fn color_rgb_format(mut self, new_value: bool) -> CalendarListUpdateCall<'a, C, NC, A> { + self._color_rgb_format = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an entry on the user's calendar list. +/// +/// A builder for the *delete* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().delete("calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarListDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarListDeleteCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns an entry on the user's calendar list. +/// +/// A builder for the *get* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().get("calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarListGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CalendarListEntry)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarListGetCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns entries on the user's calendar list. +/// +/// A builder for the *list* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().list() +/// .sync_token("consetetur") +/// .show_hidden(false) +/// .show_deleted(true) +/// .page_token("Lorem") +/// .min_access_role("gubergren") +/// .max_results(-20) +/// .doit(); +/// # } +/// ``` +pub struct CalendarListListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _sync_token: Option, + _show_hidden: Option, + _show_deleted: Option, + _page_token: Option, + _min_access_role: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CalendarList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._show_hidden { + params.push(("showHidden", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._min_access_role { + params.push(("minAccessRole", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "syncToken", "showHidden", "showDeleted", "pageToken", "minAccessRole", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. If only read-only fields such as calendar properties or ACLs have changed, the entry won't be returned. All entries deleted and hidden since the previous list request will always be in the result set and it is not allowed to set showDeleted neither showHidden to False. + /// To ensure client state consistency minAccessRole query parameter cannot be specified together with nextSyncToken. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> CalendarListListCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *show hidden* query property to the given value. + /// + /// + /// Whether to show hidden entries. Optional. The default is False. + pub fn show_hidden(mut self, new_value: bool) -> CalendarListListCall<'a, C, NC, A> { + self._show_hidden = Some(new_value); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted calendar list entries in the result. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> CalendarListListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> CalendarListListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *min access role* query property to the given value. + /// + /// + /// The minimum access role for the user in the returned entires. Optional. The default is no restriction. + pub fn min_access_role(mut self, new_value: &str) -> CalendarListListCall<'a, C, NC, A> { + self._min_access_role = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> CalendarListListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds an entry to the user's calendar list. +/// +/// A builder for the *insert* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::CalendarListEntry; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CalendarListEntry = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().insert(&req) +/// .color_rgb_format(false) +/// .doit(); +/// # } +/// ``` +pub struct CalendarListInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: CalendarListEntry, + _color_rgb_format: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CalendarListEntry)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._color_rgb_format { + params.push(("colorRgbFormat", value.to_string())); + } + for &field in ["alt", "colorRgbFormat"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CalendarListEntry) -> CalendarListInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *color rgb format* query property to the given value. + /// + /// + /// Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId field will be set to the best matching option automatically. Optional. The default is False. + pub fn color_rgb_format(mut self, new_value: bool) -> CalendarListInsertCall<'a, C, NC, A> { + self._color_rgb_format = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an entry on the user's calendar list. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::CalendarListEntry; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CalendarListEntry = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().patch(&req, "calendarId") +/// .color_rgb_format(true) +/// .doit(); +/// # } +/// ``` +pub struct CalendarListPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: CalendarListEntry, + _calendar_id: String, + _color_rgb_format: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CalendarListEntry)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._color_rgb_format { + params.push(("colorRgbFormat", value.to_string())); + } + for &field in ["alt", "calendarId", "colorRgbFormat"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CalendarListEntry) -> CalendarListPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarListPatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *color rgb format* query property to the given value. + /// + /// + /// Whether to use the foregroundColor and backgroundColor fields to write the calendar colors (RGB). If this feature is used, the index-based colorId field will be set to the best matching option automatically. Optional. The default is False. + pub fn color_rgb_format(mut self, new_value: bool) -> CalendarListPatchCall<'a, C, NC, A> { + self._color_rgb_format = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes to CalendarList resources. +/// +/// A builder for the *watch* method supported by a *calendarList* resource. +/// It is not used directly, but through a `CalendarListMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendar_list().watch(&req) +/// .sync_token("rebum.") +/// .show_hidden(true) +/// .show_deleted(true) +/// .page_token("vero") +/// .min_access_role("sadipscing") +/// .max_results(-88) +/// .doit(); +/// # } +/// ``` +pub struct CalendarListWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Channel, + _sync_token: Option, + _show_hidden: Option, + _show_deleted: Option, + _page_token: Option, + _min_access_role: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarListWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarListWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendarList.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._show_hidden { + params.push(("showHidden", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._min_access_role { + params.push(("minAccessRole", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "syncToken", "showHidden", "showDeleted", "pageToken", "minAccessRole", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/users/me/calendarList/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> CalendarListWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. If only read-only fields such as calendar properties or ACLs have changed, the entry won't be returned. All entries deleted and hidden since the previous list request will always be in the result set and it is not allowed to set showDeleted neither showHidden to False. + /// To ensure client state consistency minAccessRole query parameter cannot be specified together with nextSyncToken. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> CalendarListWatchCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *show hidden* query property to the given value. + /// + /// + /// Whether to show hidden entries. Optional. The default is False. + pub fn show_hidden(mut self, new_value: bool) -> CalendarListWatchCall<'a, C, NC, A> { + self._show_hidden = Some(new_value); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted calendar list entries in the result. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> CalendarListWatchCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> CalendarListWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *min access role* query property to the given value. + /// + /// + /// The minimum access role for the user in the returned entires. Optional. The default is no restriction. + pub fn min_access_role(mut self, new_value: &str) -> CalendarListWatchCall<'a, C, NC, A> { + self._min_access_role = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> CalendarListWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarListWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarListWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarListWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates metadata for a calendar. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Calendar; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Calendar = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().patch(&req, "calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Calendar, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Calendar)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Calendar) -> CalendarPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarPatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a secondary calendar. Use calendars.clear for clearing all events on primary calendars. +/// +/// A builder for the *delete* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().delete("calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarDeleteCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns metadata for a calendar. +/// +/// A builder for the *get* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().get("calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Calendar)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarGetCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Clears a primary calendar. This operation deletes all events associated with the primary calendar of an account. +/// +/// A builder for the *clear* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().clear("calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarClearCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarClearCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarClearCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.clear", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/clear".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarClearCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarClearCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarClearCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarClearCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a secondary calendar. +/// +/// A builder for the *insert* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Calendar; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Calendar = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().insert(&req) +/// .doit(); +/// # } +/// ``` +pub struct CalendarInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Calendar, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Calendar)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Calendar) -> CalendarInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates metadata for a calendar. +/// +/// A builder for the *update* method supported by a *calendar* resource. +/// It is not used directly, but through a `CalendarMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Calendar; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Calendar = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.calendars().update(&req, "calendarId") +/// .doit(); +/// # } +/// ``` +pub struct CalendarUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Calendar, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CalendarUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CalendarUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Calendar)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.calendars.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Calendar) -> CalendarUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> CalendarUpdateCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CalendarUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CalendarUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CalendarUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes to ACL resources. +/// +/// A builder for the *watch* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().watch(&req, "calendarId") +/// .sync_token("clita") +/// .show_deleted(true) +/// .page_token("takimata") +/// .max_results(-40) +/// .doit(); +/// # } +/// ``` +pub struct AclWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Channel, + _calendar_id: String, + _sync_token: Option, + _show_deleted: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "calendarId", "syncToken", "showDeleted", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> AclWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclWatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All entries deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> AclWatchCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted ACLs in the result. Deleted ACLs are represented by role equal to "none". Deleted ACLs will always be included if syncToken is provided. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> AclWatchCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> AclWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> AclWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an access control rule. +/// +/// A builder for the *insert* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::AclRule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AclRule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().insert(&req, "calendarId") +/// .doit(); +/// # } +/// ``` +pub struct AclInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: AclRule, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AclRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AclRule) -> AclInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclInsertCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an access control rule. +/// +/// A builder for the *update* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::AclRule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AclRule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().update(&req, "calendarId", "ruleId") +/// .doit(); +/// # } +/// ``` +pub struct AclUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: AclRule, + _calendar_id: String, + _rule_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AclRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("ruleId", self._rule_id.to_string())); + for &field in ["alt", "calendarId", "ruleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl/{ruleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{ruleId}", "ruleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "ruleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AclRule) -> AclUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclUpdateCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *rule id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ACL rule identifier. + pub fn rule_id(mut self, new_value: &str) -> AclUpdateCall<'a, C, NC, A> { + self._rule_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an access control rule. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::AclRule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AclRule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().patch(&req, "calendarId", "ruleId") +/// .doit(); +/// # } +/// ``` +pub struct AclPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: AclRule, + _calendar_id: String, + _rule_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AclRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("ruleId", self._rule_id.to_string())); + for &field in ["alt", "calendarId", "ruleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl/{ruleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{ruleId}", "ruleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "ruleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AclRule) -> AclPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclPatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *rule id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ACL rule identifier. + pub fn rule_id(mut self, new_value: &str) -> AclPatchCall<'a, C, NC, A> { + self._rule_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the rules in the access control list for the calendar. +/// +/// A builder for the *list* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().list("calendarId") +/// .sync_token("ea") +/// .show_deleted(false) +/// .page_token("rebum.") +/// .max_results(-33) +/// .doit(); +/// # } +/// ``` +pub struct AclListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _sync_token: Option, + _show_deleted: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Acl)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "calendarId", "syncToken", "showDeleted", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclListCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All entries deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False. + /// If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> AclListCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted ACLs in the result. Deleted ACLs are represented by role equal to "none". Deleted ACLs will always be included if syncToken is provided. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> AclListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> AclListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of entries returned on one result page. By default the value is 100 entries. The page size can never be larger than 250 entries. Optional. + pub fn max_results(mut self, new_value: i32) -> AclListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an access control rule. +/// +/// A builder for the *delete* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().delete("calendarId", "ruleId") +/// .doit(); +/// # } +/// ``` +pub struct AclDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _rule_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("ruleId", self._rule_id.to_string())); + for &field in ["calendarId", "ruleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl/{ruleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{ruleId}", "ruleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "ruleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclDeleteCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *rule id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ACL rule identifier. + pub fn rule_id(mut self, new_value: &str) -> AclDeleteCall<'a, C, NC, A> { + self._rule_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns an access control rule. +/// +/// A builder for the *get* method supported by a *acl* resource. +/// It is not used directly, but through a `AclMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.acl().get("calendarId", "ruleId") +/// .doit(); +/// # } +/// ``` +pub struct AclGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _rule_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AclGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AclGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AclRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.acl.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("ruleId", self._rule_id.to_string())); + for &field in ["alt", "calendarId", "ruleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/acl/{ruleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{ruleId}", "ruleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "ruleId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> AclGetCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *rule id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ACL rule identifier. + pub fn rule_id(mut self, new_value: &str) -> AclGetCall<'a, C, NC, A> { + self._rule_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AclGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AclGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AclGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Stop watching resources through this channel +/// +/// A builder for the *stop* method supported by a *channel* resource. +/// It is not used directly, but through a `ChannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.channels().stop(&req) +/// .doit(); +/// # } +/// ``` +pub struct ChannelStopCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Channel, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChannelStopCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelStopCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.channels.stop", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in [].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/channels/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ChannelStopCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the color definitions for calendars and events. +/// +/// A builder for the *get* method supported by a *color* resource. +/// It is not used directly, but through a `ColorMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.colors().get() +/// .doit(); +/// # } +/// ``` +pub struct ColorGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ColorGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ColorGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Colors)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.colors.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/colors".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ColorGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ColorGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ColorGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an event. +/// +/// A builder for the *delete* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().delete("calendarId", "eventId") +/// .send_notifications(false) +/// .doit(); +/// # } +/// ``` +pub struct EventDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _event_id: String, + _send_notifications: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + for &field in ["calendarId", "eventId", "sendNotifications"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventDeleteCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event identifier. + pub fn event_id(mut self, new_value: &str) -> EventDeleteCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the deletion of the event. Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventDeleteCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an event. +/// +/// A builder for the *insert* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Event; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Event = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().insert(&req, "calendarId") +/// .send_notifications(true) +/// .max_attendees(-62) +/// .doit(); +/// # } +/// ``` +pub struct EventInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Event, + _calendar_id: String, + _send_notifications: Option, + _max_attendees: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + for &field in ["alt", "calendarId", "sendNotifications", "maxAttendees"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Event) -> EventInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventInsertCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the creation of the new event. Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventInsertCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventInsertCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Imports an event. This operation is used to add a private copy of an existing event to a calendar. +/// +/// A builder for the *import* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Event; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Event = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().import(&req, "calendarId") +/// .doit(); +/// # } +/// ``` +pub struct EventImportCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Event, + _calendar_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventImportCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventImportCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.import", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + for &field in ["alt", "calendarId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/import".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Event) -> EventImportCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventImportCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventImportCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventImportCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventImportCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns instances of the specified recurring event. +/// +/// A builder for the *instances* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().instances("calendarId", "eventId") +/// .time_zone("sea") +/// .time_min("labore") +/// .time_max("ipsum") +/// .show_deleted(true) +/// .page_token("dolores") +/// .original_start("sit") +/// .max_results(-41) +/// .max_attendees(-37) +/// .always_include_email(false) +/// .doit(); +/// # } +/// ``` +pub struct EventInstanceCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _event_id: String, + _time_zone: Option, + _time_min: Option, + _time_max: Option, + _show_deleted: Option, + _page_token: Option, + _original_start: Option, + _max_results: Option, + _max_attendees: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventInstanceCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventInstanceCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Events)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.instances", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + if let Some(value) = self._time_zone { + params.push(("timeZone", value.to_string())); + } + if let Some(value) = self._time_min { + params.push(("timeMin", value.to_string())); + } + if let Some(value) = self._time_max { + params.push(("timeMax", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._original_start { + params.push(("originalStart", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "eventId", "timeZone", "timeMin", "timeMax", "showDeleted", "pageToken", "originalStart", "maxResults", "maxAttendees", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}/instances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Recurring event identifier. + pub fn event_id(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *time zone* query property to the given value. + /// + /// + /// Time zone used in the response. Optional. The default is the time zone of the calendar. + pub fn time_zone(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._time_zone = Some(new_value.to_string()); + self + } + /// Sets the *time min* query property to the given value. + /// + /// + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + pub fn time_min(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._time_min = Some(new_value.to_string()); + self + } + /// Sets the *time max* query property to the given value. + /// + /// + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + pub fn time_max(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._time_max = Some(new_value.to_string()); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events will still be included if singleEvents is False. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> EventInstanceCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *original start* query property to the given value. + /// + /// + /// The original start time of the instance in the result. Optional. + pub fn original_start(mut self, new_value: &str) -> EventInstanceCall<'a, C, NC, A> { + self._original_start = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of events returned on one result page. By default the value is 250 events. The page size can never be larger than 2500 events. Optional. + pub fn max_results(mut self, new_value: i32) -> EventInstanceCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventInstanceCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventInstanceCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventInstanceCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventInstanceCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventInstanceCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns an event. +/// +/// A builder for the *get* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().get("calendarId", "eventId") +/// .time_zone("accusam") +/// .max_attendees(-13) +/// .always_include_email(false) +/// .doit(); +/// # } +/// ``` +pub struct EventGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _event_id: String, + _time_zone: Option, + _max_attendees: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + if let Some(value) = self._time_zone { + params.push(("timeZone", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "eventId", "timeZone", "maxAttendees", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventGetCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event identifier. + pub fn event_id(mut self, new_value: &str) -> EventGetCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *time zone* query property to the given value. + /// + /// + /// Time zone used in the response. Optional. The default is the time zone of the calendar. + pub fn time_zone(mut self, new_value: &str) -> EventGetCall<'a, C, NC, A> { + self._time_zone = Some(new_value.to_string()); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventGetCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventGetCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns events on the specified calendar. +/// +/// A builder for the *list* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().list("calendarId") +/// .updated_min("est") +/// .time_zone("clita") +/// .time_min("invidunt") +/// .time_max("ut") +/// .sync_token("dolores") +/// .single_events(true) +/// .show_hidden_invitations(false) +/// .show_deleted(true) +/// .add_shared_extended_property("sed") +/// .q("aliquyam") +/// .add_private_extended_property("ea") +/// .page_token("ea") +/// .order_by("et") +/// .max_results(-48) +/// .max_attendees(-41) +/// .i_cal_uid("kasd") +/// .always_include_email(false) +/// .doit(); +/// # } +/// ``` +pub struct EventListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _updated_min: Option, + _time_zone: Option, + _time_min: Option, + _time_max: Option, + _sync_token: Option, + _single_events: Option, + _show_hidden_invitations: Option, + _show_deleted: Option, + _shared_extended_property: Vec, + _q: Option, + _private_extended_property: Vec, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _max_attendees: Option, + _i_cal_uid: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Events)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((20 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._time_zone { + params.push(("timeZone", value.to_string())); + } + if let Some(value) = self._time_min { + params.push(("timeMin", value.to_string())); + } + if let Some(value) = self._time_max { + params.push(("timeMax", value.to_string())); + } + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._single_events { + params.push(("singleEvents", value.to_string())); + } + if let Some(value) = self._show_hidden_invitations { + params.push(("showHiddenInvitations", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if self._shared_extended_property.len() > 0 { + let mut s = String::new(); + for f in self._shared_extended_property.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sharedExtendedProperty", s)); + } + if let Some(value) = self._q { + params.push(("q", value.to_string())); + } + if self._private_extended_property.len() > 0 { + let mut s = String::new(); + for f in self._private_extended_property.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("privateExtendedProperty", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._i_cal_uid { + params.push(("iCalUID", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "updatedMin", "timeZone", "timeMin", "timeMax", "syncToken", "singleEvents", "showHiddenInvitations", "showDeleted", "sharedExtendedProperty", "q", "privateExtendedProperty", "pageToken", "orderBy", "maxResults", "maxAttendees", "iCalUID", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// Lower bound for an event's last modification time (as a RFC 3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time. + pub fn updated_min(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *time zone* query property to the given value. + /// + /// + /// Time zone used in the response. Optional. The default is the time zone of the calendar. + pub fn time_zone(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._time_zone = Some(new_value.to_string()); + self + } + /// Sets the *time min* query property to the given value. + /// + /// + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + pub fn time_min(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._time_min = Some(new_value.to_string()); + self + } + /// Sets the *time max* query property to the given value. + /// + /// + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + pub fn time_max(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._time_max = Some(new_value.to_string()); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False. + /// There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state. + /// + /// These are: + /// - iCalUID + /// - orderBy + /// - privateExtendedProperty + /// - q + /// - sharedExtendedProperty + /// - timeMin + /// - timeMax + /// - updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *single events* query property to the given value. + /// + /// + /// Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves. Optional. The default is False. + pub fn single_events(mut self, new_value: bool) -> EventListCall<'a, C, NC, A> { + self._single_events = Some(new_value); + self + } + /// Sets the *show hidden invitations* query property to the given value. + /// + /// + /// Whether to include hidden invitations in the result. Optional. The default is False. + pub fn show_hidden_invitations(mut self, new_value: bool) -> EventListCall<'a, C, NC, A> { + self._show_hidden_invitations = Some(new_value); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> EventListCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Append the given value to the *shared extended property* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints. + pub fn add_shared_extended_property(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._shared_extended_property.push(new_value.to_string()); + self + } + /// Sets the *q* query property to the given value. + /// + /// + /// Free text search terms to find events that match these terms in any field, except for extended properties. Optional. + pub fn q(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._q = Some(new_value.to_string()); + self + } + /// Append the given value to the *private extended property* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints. + pub fn add_private_extended_property(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._private_extended_property.push(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// The order of the events returned in the result. Optional. The default is an unspecified, stable order. + pub fn order_by(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of events returned on one result page. By default the value is 250 events. The page size can never be larger than 2500 events. Optional. + pub fn max_results(mut self, new_value: i32) -> EventListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventListCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *i cal uid* query property to the given value. + /// + /// + /// Specifies event ID in the iCalendar format to be included in the response. Optional. + pub fn i_cal_uid(mut self, new_value: &str) -> EventListCall<'a, C, NC, A> { + self._i_cal_uid = Some(new_value.to_string()); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventListCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an event. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Event; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Event = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().patch(&req, "calendarId", "eventId") +/// .send_notifications(false) +/// .max_attendees(-37) +/// .always_include_email(false) +/// .doit(); +/// # } +/// ``` +pub struct EventPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Event, + _calendar_id: String, + _event_id: String, + _send_notifications: Option, + _max_attendees: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "eventId", "sendNotifications", "maxAttendees", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Event) -> EventPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventPatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event identifier. + pub fn event_id(mut self, new_value: &str) -> EventPatchCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventPatchCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventPatchCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventPatchCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Moves an event to another calendar, i.e. changes an event's organizer. +/// +/// A builder for the *move* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().move_("calendarId", "eventId", "destination") +/// .send_notifications(false) +/// .doit(); +/// # } +/// ``` +pub struct EventMoveCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _event_id: String, + _destination: String, + _send_notifications: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventMoveCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventMoveCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.move", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + params.push(("destination", self._destination.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + for &field in ["alt", "calendarId", "eventId", "destination", "sendNotifications"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}/move".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier of the source calendar where the event currently is on. + pub fn calendar_id(mut self, new_value: &str) -> EventMoveCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event identifier. + pub fn event_id(mut self, new_value: &str) -> EventMoveCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *destination* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier of the target calendar where the event is to be moved to. + pub fn destination(mut self, new_value: &str) -> EventMoveCall<'a, C, NC, A> { + self._destination = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the change of the event's organizer. Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventMoveCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventMoveCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventMoveCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventMoveCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an event. +/// +/// A builder for the *update* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Event; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Event = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().update(&req, "calendarId", "eventId") +/// .send_notifications(true) +/// .max_attendees(-91) +/// .always_include_email(true) +/// .doit(); +/// # } +/// ``` +pub struct EventUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Event, + _calendar_id: String, + _event_id: String, + _send_notifications: Option, + _max_attendees: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("eventId", self._event_id.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "eventId", "sendNotifications", "maxAttendees", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/{eventId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId"), ("{eventId}", "eventId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["calendarId", "eventId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Event) -> EventUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventUpdateCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *event id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event identifier. + pub fn event_id(mut self, new_value: &str) -> EventUpdateCall<'a, C, NC, A> { + self._event_id = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventUpdateCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventUpdateCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventUpdateCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Watch for changes to Events resources. +/// +/// A builder for the *watch* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// use calendar3::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().watch(&req, "calendarId") +/// .updated_min("Lorem") +/// .time_zone("diam") +/// .time_min("ut") +/// .time_max("ut") +/// .sync_token("amet.") +/// .single_events(false) +/// .show_hidden_invitations(false) +/// .show_deleted(true) +/// .add_shared_extended_property("sea") +/// .q("ut") +/// .add_private_extended_property("eirmod") +/// .page_token("sanctus") +/// .order_by("voluptua.") +/// .max_results(-99) +/// .max_attendees(-22) +/// .i_cal_uid("et") +/// .always_include_email(true) +/// .doit(); +/// # } +/// ``` +pub struct EventWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _request: Channel, + _calendar_id: String, + _updated_min: Option, + _time_zone: Option, + _time_min: Option, + _time_max: Option, + _sync_token: Option, + _single_events: Option, + _show_hidden_invitations: Option, + _show_deleted: Option, + _shared_extended_property: Vec, + _q: Option, + _private_extended_property: Vec, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _max_attendees: Option, + _i_cal_uid: Option, + _always_include_email: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((21 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._time_zone { + params.push(("timeZone", value.to_string())); + } + if let Some(value) = self._time_min { + params.push(("timeMin", value.to_string())); + } + if let Some(value) = self._time_max { + params.push(("timeMax", value.to_string())); + } + if let Some(value) = self._sync_token { + params.push(("syncToken", value.to_string())); + } + if let Some(value) = self._single_events { + params.push(("singleEvents", value.to_string())); + } + if let Some(value) = self._show_hidden_invitations { + params.push(("showHiddenInvitations", value.to_string())); + } + if let Some(value) = self._show_deleted { + params.push(("showDeleted", value.to_string())); + } + if self._shared_extended_property.len() > 0 { + let mut s = String::new(); + for f in self._shared_extended_property.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sharedExtendedProperty", s)); + } + if let Some(value) = self._q { + params.push(("q", value.to_string())); + } + if self._private_extended_property.len() > 0 { + let mut s = String::new(); + for f in self._private_extended_property.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("privateExtendedProperty", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_attendees { + params.push(("maxAttendees", value.to_string())); + } + if let Some(value) = self._i_cal_uid { + params.push(("iCalUID", value.to_string())); + } + if let Some(value) = self._always_include_email { + params.push(("alwaysIncludeEmail", value.to_string())); + } + for &field in ["alt", "calendarId", "updatedMin", "timeZone", "timeMin", "timeMax", "syncToken", "singleEvents", "showHiddenInvitations", "showDeleted", "sharedExtendedProperty", "q", "privateExtendedProperty", "pageToken", "orderBy", "maxResults", "maxAttendees", "iCalUID", "alwaysIncludeEmail"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> EventWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// Lower bound for an event's last modification time (as a RFC 3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time. + pub fn updated_min(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *time zone* query property to the given value. + /// + /// + /// Time zone used in the response. Optional. The default is the time zone of the calendar. + pub fn time_zone(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._time_zone = Some(new_value.to_string()); + self + } + /// Sets the *time min* query property to the given value. + /// + /// + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + pub fn time_min(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._time_min = Some(new_value.to_string()); + self + } + /// Sets the *time max* query property to the given value. + /// + /// + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + pub fn time_max(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._time_max = Some(new_value.to_string()); + self + } + /// Sets the *sync token* query property to the given value. + /// + /// + /// Token obtained from the nextSyncToken field returned on the last page of results from the previous list request. It makes the result of this list request contain only entries that have changed since then. All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False. + /// There are several query parameters that cannot be specified together with nextSyncToken to ensure consistency of the client state. + /// + /// These are: + /// - iCalUID + /// - orderBy + /// - privateExtendedProperty + /// - q + /// - sharedExtendedProperty + /// - timeMin + /// - timeMax + /// - updatedMin If the syncToken expires, the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken. + /// Learn more about incremental synchronization. + /// Optional. The default is to return all entries. + pub fn sync_token(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._sync_token = Some(new_value.to_string()); + self + } + /// Sets the *single events* query property to the given value. + /// + /// + /// Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves. Optional. The default is False. + pub fn single_events(mut self, new_value: bool) -> EventWatchCall<'a, C, NC, A> { + self._single_events = Some(new_value); + self + } + /// Sets the *show hidden invitations* query property to the given value. + /// + /// + /// Whether to include hidden invitations in the result. Optional. The default is False. + pub fn show_hidden_invitations(mut self, new_value: bool) -> EventWatchCall<'a, C, NC, A> { + self._show_hidden_invitations = Some(new_value); + self + } + /// Sets the *show deleted* query property to the given value. + /// + /// + /// Whether to include deleted events (with status equals "cancelled") in the result. Cancelled instances of recurring events (but not the underlying recurring event) will still be included if showDeleted and singleEvents are both False. If showDeleted and singleEvents are both True, only single instances of deleted events (but not the underlying recurring events) are returned. Optional. The default is False. + pub fn show_deleted(mut self, new_value: bool) -> EventWatchCall<'a, C, NC, A> { + self._show_deleted = Some(new_value); + self + } + /// Append the given value to the *shared extended property* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints. + pub fn add_shared_extended_property(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._shared_extended_property.push(new_value.to_string()); + self + } + /// Sets the *q* query property to the given value. + /// + /// + /// Free text search terms to find events that match these terms in any field, except for extended properties. Optional. + pub fn q(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._q = Some(new_value.to_string()); + self + } + /// Append the given value to the *private extended property* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints. + pub fn add_private_extended_property(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._private_extended_property.push(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Token specifying which result page to return. Optional. + pub fn page_token(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *order by* query property to the given value. + /// + /// + /// The order of the events returned in the result. Optional. The default is an unspecified, stable order. + pub fn order_by(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of events returned on one result page. By default the value is 250 events. The page size can never be larger than 2500 events. Optional. + pub fn max_results(mut self, new_value: i32) -> EventWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *max attendees* query property to the given value. + /// + /// + /// The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional. + pub fn max_attendees(mut self, new_value: i32) -> EventWatchCall<'a, C, NC, A> { + self._max_attendees = Some(new_value); + self + } + /// Sets the *i cal uid* query property to the given value. + /// + /// + /// Specifies event ID in the iCalendar format to be included in the response. Optional. + pub fn i_cal_uid(mut self, new_value: &str) -> EventWatchCall<'a, C, NC, A> { + self._i_cal_uid = Some(new_value.to_string()); + self + } + /// Sets the *always include email* query property to the given value. + /// + /// + /// Whether to always include a value in the email field for the organizer, creator and attendees, even if no real email is available (i.e. a generated, non-working value will be provided). The use of this option is discouraged and should only be used by clients which cannot handle the absence of an email address value in the mentioned places. Optional. The default is False. + pub fn always_include_email(mut self, new_value: bool) -> EventWatchCall<'a, C, NC, A> { + self._always_include_email = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an event based on a simple text string. +/// +/// A builder for the *quickAdd* method supported by a *event* resource. +/// It is not used directly, but through a `EventMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-calendar3" as calendar3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use calendar3::CalendarHub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CalendarHub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.events().quick_add("calendarId", "text") +/// .send_notifications(true) +/// .doit(); +/// # } +/// ``` +pub struct EventQuickAddCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CalendarHub, + _calendar_id: String, + _text: String, + _send_notifications: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventQuickAddCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventQuickAddCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Event)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "calendar.events.quickAdd", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("calendarId", self._calendar_id.to_string())); + params.push(("text", self._text.to_string())); + if let Some(value) = self._send_notifications { + params.push(("sendNotifications", value.to_string())); + } + for &field in ["alt", "calendarId", "text", "sendNotifications"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/quickAdd".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{calendarId}", "calendarId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["calendarId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *calendar id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Calendar identifier. + pub fn calendar_id(mut self, new_value: &str) -> EventQuickAddCall<'a, C, NC, A> { + self._calendar_id = new_value.to_string(); + self + } + /// Sets the *text* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The text describing the event to be created. + pub fn text(mut self, new_value: &str) -> EventQuickAddCall<'a, C, NC, A> { + self._text = new_value.to_string(); + self + } + /// Sets the *send notifications* query property to the given value. + /// + /// + /// Whether to send notifications about the creation of the event. Optional. The default is False. + pub fn send_notifications(mut self, new_value: bool) -> EventQuickAddCall<'a, C, NC, A> { + self._send_notifications = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventQuickAddCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventQuickAddCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventQuickAddCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/cloudlatencytest2/Cargo.toml b/gen/cloudlatencytest2/Cargo.toml new file mode 100644 index 0000000000..ebbc6acda3 --- /dev/null +++ b/gen/cloudlatencytest2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudlatencytest2" +version = "0.1.0+20150206" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with cloudlatencytest (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudlatencytest2" +homepage = "" +documentation = "http://byron.github.io/google-apis-rs/google-cloudlatencytest2" +license = "MIT" +keywords = ["cloudlatencytest", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/cloudlatencytest2/LICENSE.md b/gen/cloudlatencytest2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudlatencytest2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/cloudlatencytest2/README.md b/gen/cloudlatencytest2/README.md new file mode 100644 index 0000000000..85825258b6 --- /dev/null +++ b/gen/cloudlatencytest2/README.md @@ -0,0 +1,166 @@ + +The `google-cloudlatencytest2` library allows access to all features of the *Google cloudlatencytest* service. + +This documentation was generated from *cloudlatencytest* crate version *0.1.0+20150206*, where *20150206* is the exact revision of the *cloudlatencytest:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/struct.Cloudlatencytest.html) ... + +* statscollection + * [*updateaggregatedstats*](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/struct.StatscollectionUpdateaggregatedstatCall.html) and [*updatestats*](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/struct.StatscollectionUpdatestatCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/struct.Cloudlatencytest.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.statscollection().updatestats(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-cloudlatencytest2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-cloudlatencytest2" as cloudlatencytest2; +use cloudlatencytest2::Stats; +use cloudlatencytest2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use cloudlatencytest2::Cloudlatencytest; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Stats = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.statscollection().updatestats(&req) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-cloudlatencytest2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **cloudlatencytest2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/cloudlatencytest2/src/cmn.rs b/gen/cloudlatencytest2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/cloudlatencytest2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/cloudlatencytest2/src/lib.rs b/gen/cloudlatencytest2/src/lib.rs new file mode 100644 index 0000000000..8ed1c12b46 --- /dev/null +++ b/gen/cloudlatencytest2/src/lib.rs @@ -0,0 +1,968 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *cloudlatencytest* crate version *0.1.0+20150206*, where *20150206* is the exact revision of the *cloudlatencytest:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudlatencytest2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Cloudlatencytest.html) ... +//! +//! * statscollection +//! * [*updateaggregatedstats*](struct.StatscollectionUpdateaggregatedstatCall.html) and [*updatestats*](struct.StatscollectionUpdatestatCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Cloudlatencytest.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.statscollection().updatestats(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-cloudlatencytest2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-cloudlatencytest2" as cloudlatencytest2; +//! use cloudlatencytest2::Stats; +//! use cloudlatencytest2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use cloudlatencytest2::Cloudlatencytest; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Stats = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.statscollection().updatestats(&req) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View monitoring data for all of your Google Cloud and API projects + MonitoringReadonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::MonitoringReadonly => "https://www.googleapis.com/auth/monitoring.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::MonitoringReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Cloudlatencytest related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudlatencytest2" as cloudlatencytest2; +/// use cloudlatencytest2::Stats; +/// use cloudlatencytest2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudlatencytest2::Cloudlatencytest; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Stats = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.statscollection().updatestats(&req) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Cloudlatencytest { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Cloudlatencytest {} + +impl<'a, C, NC, A> Cloudlatencytest + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Cloudlatencytest { + Cloudlatencytest { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn statscollection(&'a self) -> StatscollectionMethods<'a, C, NC, A> { + StatscollectionMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct IntValue { + /// no description provided + pub value: String, + /// no description provided + pub label: String, +} + +impl Part for IntValue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [updatestats statscollection](struct.StatscollectionUpdatestatCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct Stats { + /// no description provided + #[serde(alias="stringValues")] + pub string_values: Option>, + /// no description provided + #[serde(alias="intValues")] + pub int_values: Option>, + /// no description provided + #[serde(alias="doubleValues")] + pub double_values: Option>, + /// no description provided + pub time: Option, +} + +impl RequestValue for Stats {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct StringValue { + /// no description provided + pub value: String, + /// no description provided + pub label: String, +} + +impl Part for StringValue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [updateaggregatedstats statscollection](struct.StatscollectionUpdateaggregatedstatCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AggregatedStats { + /// no description provided + pub stats: Option>, +} + +impl RequestValue for AggregatedStats {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [updateaggregatedstats statscollection](struct.StatscollectionUpdateaggregatedstatCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AggregatedStatsReply { + /// no description provided + #[serde(alias="testValue")] + pub test_value: String, +} + +impl ResponseResult for AggregatedStatsReply {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DoubleValue { + /// no description provided + pub value: f32, + /// no description provided + pub label: String, +} + +impl Part for DoubleValue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [updatestats statscollection](struct.StatscollectionUpdatestatCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct StatsReply { + /// no description provided + #[serde(alias="testValue")] + pub test_value: String, +} + +impl ResponseResult for StatsReply {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *statscollection* resources. +/// It is not used directly, but through the `Cloudlatencytest` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudlatencytest2" as cloudlatencytest2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudlatencytest2::Cloudlatencytest; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `updateaggregatedstats(...)` and `updatestats(...)` +/// // to build up your call. +/// let rb = hub.statscollection(); +/// # } +/// ``` +pub struct StatscollectionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Cloudlatencytest, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for StatscollectionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> StatscollectionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// RPC to update the new TCP stats. + pub fn updateaggregatedstats(&self, request: &AggregatedStats) -> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> { + StatscollectionUpdateaggregatedstatCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// RPC to update the new TCP stats. + pub fn updatestats(&self, request: &Stats) -> StatscollectionUpdatestatCall<'a, C, NC, A> { + StatscollectionUpdatestatCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// RPC to update the new TCP stats. +/// +/// A builder for the *updateaggregatedstats* method supported by a *statscollection* resource. +/// It is not used directly, but through a `StatscollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudlatencytest2" as cloudlatencytest2; +/// use cloudlatencytest2::AggregatedStats; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudlatencytest2::Cloudlatencytest; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AggregatedStats = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.statscollection().updateaggregatedstats(&req) +/// .doit(); +/// # } +/// ``` +pub struct StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Cloudlatencytest, + _request: AggregatedStats, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AggregatedStatsReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudlatencytest.statscollection.updateaggregatedstats", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudlatencytest-pa.googleapis.com/v2/statscollection/updateaggregatedstats".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::MonitoringReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AggregatedStats) -> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StatscollectionUpdateaggregatedstatCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// RPC to update the new TCP stats. +/// +/// A builder for the *updatestats* method supported by a *statscollection* resource. +/// It is not used directly, but through a `StatscollectionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudlatencytest2" as cloudlatencytest2; +/// use cloudlatencytest2::Stats; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudlatencytest2::Cloudlatencytest; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudlatencytest::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Stats = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.statscollection().updatestats(&req) +/// .doit(); +/// # } +/// ``` +pub struct StatscollectionUpdatestatCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Cloudlatencytest, + _request: Stats, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for StatscollectionUpdatestatCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> StatscollectionUpdatestatCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, StatsReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudlatencytest.statscollection.updatestats", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudlatencytest-pa.googleapis.com/v2/statscollection/updatestats".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::MonitoringReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Stats) -> StatscollectionUpdatestatCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> StatscollectionUpdatestatCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> StatscollectionUpdatestatCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> StatscollectionUpdatestatCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/cloudmonitoring2_beta2/Cargo.toml b/gen/cloudmonitoring2_beta2/Cargo.toml new file mode 100644 index 0000000000..b3feca42ce --- /dev/null +++ b/gen/cloudmonitoring2_beta2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudmonitoring2_beta2" +version = "0.1.0+20150305" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Cloud Monitoring (protocol v2beta2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudmonitoring2_beta2" +homepage = "https://cloud.google.com/monitoring/v2beta2/" +documentation = "http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2" +license = "MIT" +keywords = ["cloudmonitoring", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/cloudmonitoring2_beta2/LICENSE.md b/gen/cloudmonitoring2_beta2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudmonitoring2_beta2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/cloudmonitoring2_beta2/README.md b/gen/cloudmonitoring2_beta2/README.md new file mode 100644 index 0000000000..09618a0574 --- /dev/null +++ b/gen/cloudmonitoring2_beta2/README.md @@ -0,0 +1,178 @@ + +The `google-cloudmonitoring2_beta2` library allows access to all features of the *Google Cloud Monitoring* service. + +This documentation was generated from *Cloud Monitoring* crate version *0.1.0+20150305*, where *20150305* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Cloud Monitoring* *v2_beta2* API can be found at the +[official documentation site](https://cloud.google.com/monitoring/v2beta2/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.CloudMonitoring.html) ... + +* [metric descriptors](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.MetricDescriptor.html) + * [*create*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.MetricDescriptorCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.MetricDescriptorDeleteCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.MetricDescriptorListCall.html) +* timeseries + * [*list*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.TimeseryListCall.html) and [*write*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.TimeseryWriteCall.html) +* [timeseries descriptors](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.TimeseriesDescriptor.html) + * [*list*](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.TimeseriesDescriptorListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/struct.CloudMonitoring.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.metric_descriptors().list(...).doit() +let r = hub.metric_descriptors().delete(...).doit() +let r = hub.metric_descriptors().create(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-cloudmonitoring2_beta2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +use cloudmonitoring2_beta2::ListMetricDescriptorsRequest; +use cloudmonitoring2_beta2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use cloudmonitoring2_beta2::CloudMonitoring; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: ListMetricDescriptorsRequest = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.metric_descriptors().list(&req, "project") + .query("sit") + .page_token("Stet") + .count(-42) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **cloudmonitoring2_beta2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/cloudmonitoring2_beta2/src/cmn.rs b/gen/cloudmonitoring2_beta2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/cloudmonitoring2_beta2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/cloudmonitoring2_beta2/src/lib.rs b/gen/cloudmonitoring2_beta2/src/lib.rs new file mode 100644 index 0000000000..3a98d5c302 --- /dev/null +++ b/gen/cloudmonitoring2_beta2/src/lib.rs @@ -0,0 +1,2822 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Cloud Monitoring* crate version *0.1.0+20150305*, where *20150305* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Cloud Monitoring* *v2_beta2* API can be found at the +//! [official documentation site](https://cloud.google.com/monitoring/v2beta2/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudmonitoring2_beta2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.CloudMonitoring.html) ... +//! +//! * [metric descriptors](struct.MetricDescriptor.html) +//! * [*create*](struct.MetricDescriptorCreateCall.html), [*delete*](struct.MetricDescriptorDeleteCall.html) and [*list*](struct.MetricDescriptorListCall.html) +//! * timeseries +//! * [*list*](struct.TimeseryListCall.html) and [*write*](struct.TimeseryWriteCall.html) +//! * [timeseries descriptors](struct.TimeseriesDescriptor.html) +//! * [*list*](struct.TimeseriesDescriptorListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.CloudMonitoring.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.metric_descriptors().list(...).doit() +//! let r = hub.metric_descriptors().delete(...).doit() +//! let r = hub.metric_descriptors().create(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-cloudmonitoring2_beta2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +//! use cloudmonitoring2_beta2::ListMetricDescriptorsRequest; +//! use cloudmonitoring2_beta2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use cloudmonitoring2_beta2::CloudMonitoring; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: ListMetricDescriptorsRequest = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.metric_descriptors().list(&req, "project") +//! .query("dolores") +//! .page_token("kasd") +//! .count(-22) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and write monitoring data for all of your Google and third-party Cloud and API projects + Monitoring, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Monitoring => "https://www.googleapis.com/auth/monitoring", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Monitoring + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all CloudMonitoring related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::ListMetricDescriptorsRequest; +/// use cloudmonitoring2_beta2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ListMetricDescriptorsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metric_descriptors().list(&req, "project") +/// .query("justo") +/// .page_token("amet.") +/// .count(-81) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct CloudMonitoring { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for CloudMonitoring {} + +impl<'a, C, NC, A> CloudMonitoring + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> CloudMonitoring { + CloudMonitoring { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn metric_descriptors(&'a self) -> MetricDescriptorMethods<'a, C, NC, A> { + MetricDescriptorMethods { hub: &self } + } + pub fn timeseries(&'a self) -> TimeseryMethods<'a, C, NC, A> { + TimeseryMethods { hub: &self } + } + pub fn timeseries_descriptors(&'a self) -> TimeseriesDescriptorMethods<'a, C, NC, A> { + TimeseriesDescriptorMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// The underflow bucket is a special bucket that does not have the lowerBound field; it includes all of the events that are less than its upper bound. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PointDistributionUnderflowBucket { + /// The number of events whose values are in the interval defined by this bucket. + pub count: String, + /// The upper bound of the value interval of this bucket (exclusive). + #[serde(alias="upperBound")] + pub upper_bound: f64, +} + +impl Part for PointDistributionUnderflowBucket {} + + +/// The response of cloudmonitoring.metricDescriptors.list. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list metric descriptors](struct.MetricDescriptorListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListMetricDescriptorsResponse { + /// The returned metric descriptors. + pub metrics: Vec, + /// Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, pass this value to the pageToken query parameter. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listMetricDescriptorsResponse". + pub kind: String, +} + +impl ResponseResult for ListMetricDescriptorsResponse {} + + +/// The request of cloudmonitoring.metricDescriptors.list. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list metric descriptors](struct.MetricDescriptorListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ListMetricDescriptorsRequest { + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listMetricDescriptorsRequest". + pub kind: Option, +} + +impl RequestValue for ListMetricDescriptorsRequest {} + + +/// The request of cloudmonitoring.timeseriesDescriptors.list +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list timeseries descriptors](struct.TimeseriesDescriptorListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ListTimeseriesDescriptorsRequest { + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listTimeseriesDescriptorsRequest". + pub kind: Option, +} + +impl RequestValue for ListTimeseriesDescriptorsRequest {} + + +/// When writing time series, TimeseriesPoint should be used instead of Timeseries, to enforce single point for each time series in the timeseries.write request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TimeseriesPoint { + /// The descriptor of this time series. + #[serde(alias="timeseriesDesc")] + pub timeseries_desc: TimeseriesDescriptor, + /// The data point in this time series snapshot. + pub point: Point, +} + +impl Part for TimeseriesPoint {} + + +/// Distribution data point value type. When writing distribution points, try to be consistent with the boundaries of your buckets. If you must modify the bucket boundaries, then do so by merging, partitioning, or appending rather than skewing them. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PointDistribution { + /// The finite buckets. + pub buckets: Vec, + /// The underflow bucket. + #[serde(alias="underflowBucket")] + pub underflow_bucket: PointDistributionUnderflowBucket, + /// The overflow bucket. + #[serde(alias="overflowBucket")] + pub overflow_bucket: PointDistributionOverflowBucket, +} + +impl Part for PointDistribution {} + + +/// A type in a metric contains information about how the metric is collected and what its data points look like. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MetricDescriptorTypeDescriptor { + /// The type of data that is written to a timeseries point for this metric. + #[serde(alias="valueType")] + pub value_type: String, + /// The method of collecting data for the metric. + #[serde(alias="metricType")] + pub metric_type: String, +} + +impl Part for MetricDescriptorTypeDescriptor {} + + +/// A label in a metric is a description of this metric, including the key of this description (what the description is), and the value for this description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MetricDescriptorLabelDescriptor { + /// Label description. + pub description: String, + /// Label key. + pub key: String, +} + +impl Part for MetricDescriptorLabelDescriptor {} + + +/// The histogram's bucket. Buckets that form the histogram of a distribution value. If the upper bound of a bucket, say U1, does not equal the lower bound of the next bucket, say L2, this means that there is no event in [U1, L2). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PointDistributionBucket { + /// The number of events whose values are in the interval defined by this bucket. + pub count: String, + /// The lower bound of the value interval of this bucket (inclusive). + #[serde(alias="lowerBound")] + pub lower_bound: f64, + /// The upper bound of the value interval of this bucket (exclusive). + #[serde(alias="upperBound")] + pub upper_bound: f64, +} + +impl Part for PointDistributionBucket {} + + +/// The request of cloudmonitoring.timeseries.list +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list timeseries](struct.TimeseryListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ListTimeseriesRequest { + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listTimeseriesRequest". + pub kind: Option, +} + +impl RequestValue for ListTimeseriesRequest {} + + +/// A metricDescriptor defines the name, label keys, and data type of a particular metric. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list metric descriptors](struct.MetricDescriptorListCall.html) (none) +/// * [delete metric descriptors](struct.MetricDescriptorDeleteCall.html) (none) +/// * [create metric descriptors](struct.MetricDescriptorCreateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MetricDescriptor { + /// The project ID to which the metric belongs. + pub project: Option, + /// Labels defined for this metric. + pub labels: Option>, + /// Description of this metric. + pub description: Option, + /// The name of this metric. + pub name: Option, + /// Type description for this metric. + #[serde(alias="typeDescriptor")] + pub type_descriptor: Option, +} + +impl RequestValue for MetricDescriptor {} +impl Resource for MetricDescriptor {} +impl ResponseResult for MetricDescriptor {} + + +/// The response of cloudmonitoring.timeseries.write +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [write timeseries](struct.TimeseryWriteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct WriteTimeseriesResponse { + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#writeTimeseriesResponse". + pub kind: String, +} + +impl ResponseResult for WriteTimeseriesResponse {} + + +/// The response of cloudmonitoring.metricDescriptors.delete. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete metric descriptors](struct.MetricDescriptorDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DeleteMetricDescriptorResponse { + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#deleteMetricDescriptorResponse". + pub kind: String, +} + +impl ResponseResult for DeleteMetricDescriptorResponse {} + + +/// The request of cloudmonitoring.timeseries.write +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [write timeseries](struct.TimeseryWriteCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct WriteTimeseriesRequest { + /// The label's name. + #[serde(alias="commonLabels")] + pub common_labels: Option>, + /// Provide time series specific labels and the data points for each time series. The labels in timeseries and the common_labels should form a complete list of labels that required by the metric. + pub timeseries: Option>, +} + +impl RequestValue for WriteTimeseriesRequest {} + + +/// Point is a single point in a time series. It consists of a start time, an end time, and a value. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Point { + /// The interval [start, end] is the time period to which the point's value applies. For gauge metrics, whose values are instantaneous measurements, this interval should be empty (start should equal end). For cumulative metrics (of which deltas and rates are special cases), the interval should be non-empty. Both start and end are RFC 3339 strings. + pub start: String, + /// The value of this data point. Either "true" or "false". + #[serde(alias="boolValue")] + pub bool_value: bool, + /// The interval [start, end] is the time period to which the point's value applies. For gauge metrics, whose values are instantaneous measurements, this interval should be empty (start should equal end). For cumulative metrics (of which deltas and rates are special cases), the interval should be non-empty. Both start and end are RFC 3339 strings. + pub end: String, + /// The value of this data point as a distribution. A distribution value can contain a list of buckets and/or an underflowBucket and an overflowBucket. The values of these points can be used to create a histogram. + #[serde(alias="distributionValue")] + pub distribution_value: PointDistribution, + /// The value of this data point in string format. + #[serde(alias="stringValue")] + pub string_value: String, + /// The value of this data point as a 64-bit integer. + #[serde(alias="int64Value")] + pub int64_value: String, + /// The value of this data point as a double-precision floating-point number. + #[serde(alias="doubleValue")] + pub double_value: f64, +} + +impl Part for Point {} + + +/// TimeseriesDescriptor identifies a single time series. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list timeseries descriptors](struct.TimeseriesDescriptorListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TimeseriesDescriptor { + /// The Developers Console project number to which this time series belongs. + pub project: Option, + /// The name of the metric. + pub metric: Option, + /// The label's name. + pub labels: Option>, +} + +impl Resource for TimeseriesDescriptor {} + + +/// The monitoring data is organized as metrics and stored as data points that are recorded over time. Each data point represents information like the CPU utilization of your virtual machine. A historical record of these data points is called a time series. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Timeseries { + /// The descriptor of this time series. + #[serde(alias="timeseriesDesc")] + pub timeseries_desc: TimeseriesDescriptor, + /// The data points of this time series. The points are listed in order of their end timestamp, from younger to older. + pub points: Vec, +} + +impl Part for Timeseries {} + + +/// The overflow bucket is a special bucket that does not have the upperBound field; it includes all of the events that are no less than its lower bound. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PointDistributionOverflowBucket { + /// The number of events whose values are in the interval defined by this bucket. + pub count: String, + /// The lower bound of the value interval of this bucket (inclusive). + #[serde(alias="lowerBound")] + pub lower_bound: f64, +} + +impl Part for PointDistributionOverflowBucket {} + + +/// The response of cloudmonitoring.timeseriesDescriptors.list +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list timeseries descriptors](struct.TimeseriesDescriptorListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListTimeseriesDescriptorsResponse { + /// Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, set this value to the pageToken query parameter. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The youngest timestamp of the interval of this query, as an RFC 3339 string. + pub youngest: String, + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listTimeseriesDescriptorsResponse". + pub kind: String, + /// The oldest timestamp of the interval of this query, as an RFC 3339 string. + pub oldest: String, + /// The returned time series descriptors. + pub timeseries: Vec, +} + +impl ResponseResult for ListTimeseriesDescriptorsResponse {} + + +/// The response of cloudmonitoring.timeseries.list +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list timeseries](struct.TimeseryListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListTimeseriesResponse { + /// Pagination token. If present, indicates that additional results are available for retrieval. To access the results past the pagination limit, set the pageToken query parameter to this value. All of the points of a time series will be returned before returning any point of the subsequent time series. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The youngest timestamp of the interval of this query as an RFC 3339 string. + pub youngest: String, + /// Identifies what kind of resource this is. Value: the fixed string "cloudmonitoring#listTimeseriesResponse". + pub kind: String, + /// The oldest timestamp of the interval of this query as an RFC 3339 string. + pub oldest: String, + /// The returned time series. + pub timeseries: Vec, +} + +impl ResponseResult for ListTimeseriesResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *timeseriesDescriptor* resources. +/// It is not used directly, but through the `CloudMonitoring` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.timeseries_descriptors(); +/// # } +/// ``` +pub struct TimeseriesDescriptorMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TimeseriesDescriptorMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TimeseriesDescriptorMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List the descriptors of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. + pub fn list(&self, request: &ListTimeseriesDescriptorsRequest, project: &str, metric: &str, youngest: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + TimeseriesDescriptorListCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _metric: metric.to_string(), + _youngest: youngest.to_string(), + _window: Default::default(), + _timespan: Default::default(), + _page_token: Default::default(), + _oldest: Default::default(), + _labels: Default::default(), + _count: Default::default(), + _aggregator: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *timesery* resources. +/// It is not used directly, but through the `CloudMonitoring` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` and `write(...)` +/// // to build up your call. +/// let rb = hub.timeseries(); +/// # } +/// ``` +pub struct TimeseryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TimeseryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TimeseryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Put data points to one or more time series for one or more metrics. If a time series does not exist, a new time series will be created. It is not allowed to write a time series point that is older than the existing youngest point of that time series. Points that are older than the existing youngest point of that time series will be discarded silently. Therefore, users should make sure that points of a time series are written sequentially in the order of their end time. + pub fn write(&self, request: &WriteTimeseriesRequest, project: &str) -> TimeseryWriteCall<'a, C, NC, A> { + TimeseryWriteCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the data points of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. + pub fn list(&self, request: &ListTimeseriesRequest, project: &str, metric: &str, youngest: &str) -> TimeseryListCall<'a, C, NC, A> { + TimeseryListCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _metric: metric.to_string(), + _youngest: youngest.to_string(), + _window: Default::default(), + _timespan: Default::default(), + _page_token: Default::default(), + _oldest: Default::default(), + _labels: Default::default(), + _count: Default::default(), + _aggregator: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *metricDescriptor* resources. +/// It is not used directly, but through the `CloudMonitoring` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create(...)`, `delete(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.metric_descriptors(); +/// # } +/// ``` +pub struct MetricDescriptorMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MetricDescriptorMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetricDescriptorMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// List metric descriptors that match the query. If the query is not set, then all of the metric descriptors will be returned. Large responses will be paginated, use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. + pub fn list(&self, request: &ListMetricDescriptorsRequest, project: &str) -> MetricDescriptorListCall<'a, C, NC, A> { + MetricDescriptorListCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _query: Default::default(), + _page_token: Default::default(), + _count: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete an existing metric. + pub fn delete(&self, project: &str, metric: &str) -> MetricDescriptorDeleteCall<'a, C, NC, A> { + MetricDescriptorDeleteCall { + hub: self.hub, + _project: project.to_string(), + _metric: metric.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create a new metric. + pub fn create(&self, request: &MetricDescriptor, project: &str) -> MetricDescriptorCreateCall<'a, C, NC, A> { + MetricDescriptorCreateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// List the descriptors of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. +/// +/// A builder for the *list* method supported by a *timeseriesDescriptor* resource. +/// It is not used directly, but through a `TimeseriesDescriptorMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::ListTimeseriesDescriptorsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ListTimeseriesDescriptorsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.timeseries_descriptors().list(&req, "project", "metric", "youngest") +/// .window("dolores") +/// .timespan("gubergren") +/// .page_token("sadipscing") +/// .oldest("aliquyam") +/// .add_labels("ea") +/// .count(-61) +/// .aggregator("justo") +/// .doit(); +/// # } +/// ``` +pub struct TimeseriesDescriptorListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _request: ListTimeseriesDescriptorsRequest, + _project: String, + _metric: String, + _youngest: String, + _window: Option, + _timespan: Option, + _page_token: Option, + _oldest: Option, + _labels: Vec, + _count: Option, + _aggregator: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TimeseriesDescriptorListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TimeseriesDescriptorListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTimeseriesDescriptorsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.timeseriesDescriptors.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("metric", self._metric.to_string())); + params.push(("youngest", self._youngest.to_string())); + if let Some(value) = self._window { + params.push(("window", value.to_string())); + } + if let Some(value) = self._timespan { + params.push(("timespan", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._oldest { + params.push(("oldest", value.to_string())); + } + if self._labels.len() > 0 { + let mut s = String::new(); + for f in self._labels.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("labels", s)); + } + if let Some(value) = self._count { + params.push(("count", value.to_string())); + } + if let Some(value) = self._aggregator { + params.push(("aggregator", value.to_string())); + } + for &field in ["alt", "project", "metric", "youngest", "window", "timespan", "pageToken", "oldest", "labels", "count", "aggregator"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/timeseriesDescriptors/{metric}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{metric}", "metric")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "metric"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ListTimeseriesDescriptorsRequest) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID to which this time series belongs. The value can be the numeric project ID or string-based project name. + pub fn project(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *metric* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Metric names are protocol-free URLs as listed in the Supported Metrics page. For example, compute.googleapis.com/instance/disk/read_ops_count. + pub fn metric(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._metric = new_value.to_string(); + self + } + /// Sets the *youngest* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp. + pub fn youngest(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._youngest = new_value.to_string(); + self + } + /// Sets the *window* query property to the given value. + /// + /// + /// The sampling window. At most one data point will be returned for each window in the requested time interval. This parameter is only valid for non-cumulative metric types. Units: + /// - m: minute + /// - h: hour + /// - d: day + /// - w: week Examples: 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead. + pub fn window(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._window = Some(new_value.to_string()); + self + } + /// Sets the *timespan* query property to the given value. + /// + /// + /// Length of the time interval to query, which is an alternative way to declare the interval: (youngest - timespan, youngest]. The timespan and oldest parameters should not be used together. Units: + /// - s: second + /// - m: minute + /// - h: hour + /// - d: day + /// - w: week Examples: 2s, 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead. + /// + /// If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest]. + pub fn timespan(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._timespan = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results. + pub fn page_token(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *oldest* query property to the given value. + /// + /// + /// Start of the time interval (exclusive), which is expressed as an RFC 3339 timestamp. If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest] + pub fn oldest(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._oldest = Some(new_value.to_string()); + self + } + /// Append the given value to the *labels* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A collection of labels for the matching time series, which are represented as: + /// - key==value: key equals the value + /// - key=~value: key regex matches the value + /// - key!=value: key does not equal the value + /// - key!~value: key regex does not match the value For example, to list all of the time series descriptors for the region us-central1, you could specify: + /// label=cloud.googleapis.com%2Flocation=~us-central1.* + pub fn add_labels(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._labels.push(new_value.to_string()); + self + } + /// Sets the *count* query property to the given value. + /// + /// + /// Maximum number of time series descriptors per page. Used for pagination. If not specified, count = 100. + pub fn count(mut self, new_value: i32) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._count = Some(new_value); + self + } + /// Sets the *aggregator* query property to the given value. + /// + /// + /// The aggregation function that will reduce the data points in each window to a single point. This parameter is only valid for non-cumulative metric types. + pub fn aggregator(mut self, new_value: &str) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._aggregator = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TimeseriesDescriptorListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TimeseriesDescriptorListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TimeseriesDescriptorListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Put data points to one or more time series for one or more metrics. If a time series does not exist, a new time series will be created. It is not allowed to write a time series point that is older than the existing youngest point of that time series. Points that are older than the existing youngest point of that time series will be discarded silently. Therefore, users should make sure that points of a time series are written sequentially in the order of their end time. +/// +/// A builder for the *write* method supported by a *timesery* resource. +/// It is not used directly, but through a `TimeseryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::WriteTimeseriesRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: WriteTimeseriesRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.timeseries().write(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct TimeseryWriteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _request: WriteTimeseriesRequest, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TimeseryWriteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TimeseryWriteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, WriteTimeseriesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.timeseries.write", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/timeseries:write".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &WriteTimeseriesRequest) -> TimeseryWriteCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID. The value can be the numeric project ID or string-based project name. + pub fn project(mut self, new_value: &str) -> TimeseryWriteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TimeseryWriteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TimeseryWriteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TimeseryWriteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List the data points of the time series that match the metric and labels values and that have data points in the interval. Large responses are paginated; use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. +/// +/// A builder for the *list* method supported by a *timesery* resource. +/// It is not used directly, but through a `TimeseryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::ListTimeseriesRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ListTimeseriesRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.timeseries().list(&req, "project", "metric", "youngest") +/// .window("ipsum") +/// .timespan("Lorem") +/// .page_token("et") +/// .oldest("duo") +/// .add_labels("aliquyam") +/// .count(-9) +/// .aggregator("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct TimeseryListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _request: ListTimeseriesRequest, + _project: String, + _metric: String, + _youngest: String, + _window: Option, + _timespan: Option, + _page_token: Option, + _oldest: Option, + _labels: Vec, + _count: Option, + _aggregator: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TimeseryListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TimeseryListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTimeseriesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.timeseries.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("metric", self._metric.to_string())); + params.push(("youngest", self._youngest.to_string())); + if let Some(value) = self._window { + params.push(("window", value.to_string())); + } + if let Some(value) = self._timespan { + params.push(("timespan", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._oldest { + params.push(("oldest", value.to_string())); + } + if self._labels.len() > 0 { + let mut s = String::new(); + for f in self._labels.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("labels", s)); + } + if let Some(value) = self._count { + params.push(("count", value.to_string())); + } + if let Some(value) = self._aggregator { + params.push(("aggregator", value.to_string())); + } + for &field in ["alt", "project", "metric", "youngest", "window", "timespan", "pageToken", "oldest", "labels", "count", "aggregator"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/timeseries/{metric}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{metric}", "metric")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "metric"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ListTimeseriesRequest) -> TimeseryListCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID to which this time series belongs. The value can be the numeric project ID or string-based project name. + pub fn project(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *metric* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Metric names are protocol-free URLs as listed in the Supported Metrics page. For example, compute.googleapis.com/instance/disk/read_ops_count. + pub fn metric(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._metric = new_value.to_string(); + self + } + /// Sets the *youngest* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp. + pub fn youngest(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._youngest = new_value.to_string(); + self + } + /// Sets the *window* query property to the given value. + /// + /// + /// The sampling window. At most one data point will be returned for each window in the requested time interval. This parameter is only valid for non-cumulative metric types. Units: + /// - m: minute + /// - h: hour + /// - d: day + /// - w: week Examples: 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead. + pub fn window(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._window = Some(new_value.to_string()); + self + } + /// Sets the *timespan* query property to the given value. + /// + /// + /// Length of the time interval to query, which is an alternative way to declare the interval: (youngest - timespan, youngest]. The timespan and oldest parameters should not be used together. Units: + /// - s: second + /// - m: minute + /// - h: hour + /// - d: day + /// - w: week Examples: 2s, 3m, 4w. Only one unit is allowed, for example: 2w3d is not allowed; you should use 17d instead. + /// + /// If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest]. + pub fn timespan(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._timespan = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results. + pub fn page_token(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *oldest* query property to the given value. + /// + /// + /// Start of the time interval (exclusive), which is expressed as an RFC 3339 timestamp. If neither oldest nor timespan is specified, the default time interval will be (youngest - 4 hours, youngest] + pub fn oldest(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._oldest = Some(new_value.to_string()); + self + } + /// Append the given value to the *labels* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A collection of labels for the matching time series, which are represented as: + /// - key==value: key equals the value + /// - key=~value: key regex matches the value + /// - key!=value: key does not equal the value + /// - key!~value: key regex does not match the value For example, to list all of the time series descriptors for the region us-central1, you could specify: + /// label=cloud.googleapis.com%2Flocation=~us-central1.* + pub fn add_labels(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._labels.push(new_value.to_string()); + self + } + /// Sets the *count* query property to the given value. + /// + /// + /// Maximum number of data points per page, which is used for pagination of results. + pub fn count(mut self, new_value: i32) -> TimeseryListCall<'a, C, NC, A> { + self._count = Some(new_value); + self + } + /// Sets the *aggregator* query property to the given value. + /// + /// + /// The aggregation function that will reduce the data points in each window to a single point. This parameter is only valid for non-cumulative metric types. + pub fn aggregator(mut self, new_value: &str) -> TimeseryListCall<'a, C, NC, A> { + self._aggregator = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TimeseryListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TimeseryListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TimeseryListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// List metric descriptors that match the query. If the query is not set, then all of the metric descriptors will be returned. Large responses will be paginated, use the nextPageToken returned in the response to request subsequent pages of results by setting the pageToken query parameter to the value of the nextPageToken. +/// +/// A builder for the *list* method supported by a *metricDescriptor* resource. +/// It is not used directly, but through a `MetricDescriptorMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::ListMetricDescriptorsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ListMetricDescriptorsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metric_descriptors().list(&req, "project") +/// .query("erat") +/// .page_token("sadipscing") +/// .count(-48) +/// .doit(); +/// # } +/// ``` +pub struct MetricDescriptorListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _request: ListMetricDescriptorsRequest, + _project: String, + _query: Option, + _page_token: Option, + _count: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetricDescriptorListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetricDescriptorListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListMetricDescriptorsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.metricDescriptors.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._count { + params.push(("count", value.to_string())); + } + for &field in ["alt", "project", "query", "pageToken", "count"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/metricDescriptors".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ListMetricDescriptorsRequest) -> MetricDescriptorListCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project id. The value can be the numeric project ID or string-based project name. + pub fn project(mut self, new_value: &str) -> MetricDescriptorListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// The query used to search against existing metrics. Separate keywords with a space; the service joins all keywords with AND, meaning that all keywords must match for a metric to be returned. If this field is omitted, all metrics are returned. If an empty string is passed with this field, no metrics are returned. + pub fn query(mut self, new_value: &str) -> MetricDescriptorListCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The pagination token, which is used to page through large result sets. Set this value to the value of the nextPageToken to retrieve the next page of results. + pub fn page_token(mut self, new_value: &str) -> MetricDescriptorListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *count* query property to the given value. + /// + /// + /// Maximum number of metric descriptors per page. Used for pagination. If not specified, count = 100. + pub fn count(mut self, new_value: i32) -> MetricDescriptorListCall<'a, C, NC, A> { + self._count = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetricDescriptorListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetricDescriptorListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetricDescriptorListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete an existing metric. +/// +/// A builder for the *delete* method supported by a *metricDescriptor* resource. +/// It is not used directly, but through a `MetricDescriptorMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metric_descriptors().delete("project", "metric") +/// .doit(); +/// # } +/// ``` +pub struct MetricDescriptorDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _project: String, + _metric: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetricDescriptorDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetricDescriptorDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeleteMetricDescriptorResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.metricDescriptors.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("metric", self._metric.to_string())); + for &field in ["alt", "project", "metric"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/metricDescriptors/{metric}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{metric}", "metric")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "metric"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID to which the metric belongs. + pub fn project(mut self, new_value: &str) -> MetricDescriptorDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *metric* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the metric. + pub fn metric(mut self, new_value: &str) -> MetricDescriptorDeleteCall<'a, C, NC, A> { + self._metric = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetricDescriptorDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetricDescriptorDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetricDescriptorDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new metric. +/// +/// A builder for the *create* method supported by a *metricDescriptor* resource. +/// It is not used directly, but through a `MetricDescriptorMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-cloudmonitoring2_beta2" as cloudmonitoring2_beta2; +/// use cloudmonitoring2_beta2::MetricDescriptor; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudmonitoring2_beta2::CloudMonitoring; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudMonitoring::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: MetricDescriptor = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metric_descriptors().create(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct MetricDescriptorCreateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a CloudMonitoring, + _request: MetricDescriptor, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetricDescriptorCreateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetricDescriptorCreateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MetricDescriptor)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudmonitoring.metricDescriptors.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/cloudmonitoring/v2beta2/projects/{project}/metricDescriptors".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Monitoring.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &MetricDescriptor) -> MetricDescriptorCreateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project id. The value can be the numeric project ID or string-based project name. + pub fn project(mut self, new_value: &str) -> MetricDescriptorCreateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetricDescriptorCreateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetricDescriptorCreateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetricDescriptorCreateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/compute1/Cargo.toml b/gen/compute1/Cargo.toml new file mode 100644 index 0000000000..a7bdf90e1e --- /dev/null +++ b/gen/compute1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-compute1" +version = "0.1.0+20150302" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with compute (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/compute1" +homepage = "https://developers.google.com/compute/docs/reference/latest/" +documentation = "http://byron.github.io/google-apis-rs/google-compute1" +license = "MIT" +keywords = ["compute", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/compute1/LICENSE.md b/gen/compute1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/compute1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/compute1/README.md b/gen/compute1/README.md new file mode 100644 index 0000000000..4648a324ec --- /dev/null +++ b/gen/compute1/README.md @@ -0,0 +1,285 @@ + +The `google-compute1` library allows access to all features of the *Google compute* service. + +This documentation was generated from *compute* crate version *0.1.0+20150302*, where *20150302* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *compute* *v1* API can be found at the +[official documentation site](https://developers.google.com/compute/docs/reference/latest/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-compute1/struct.Compute.html) ... + +* addresses + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.AddresseAggregatedListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.AddresseDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.AddresseGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.AddresseInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.AddresseListCall.html) +* [backend services](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendService.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceGetCall.html), [*get health*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceGetHealthCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServicePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-compute1/struct.BackendServiceUpdateCall.html) +* [disk types](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskType.html) + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskTypeAggregatedListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskTypeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskTypeListCall.html) +* [disks](http://byron.github.io/google-apis-rs/google-compute1/struct.Disk.html) + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskAggregatedListCall.html), [*create snapshot*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskCreateSnapshotCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.DiskListCall.html) +* [firewalls](http://byron.github.io/google-apis-rs/google-compute1/struct.Firewall.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-compute1/struct.FirewallUpdateCall.html) +* [forwarding rules](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRule.html) + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleAggregatedListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleListCall.html) and [*set target*](http://byron.github.io/google-apis-rs/google-compute1/struct.ForwardingRuleSetTargetCall.html) +* global addresses + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalAddresseDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalAddresseGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalAddresseInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalAddresseListCall.html) +* global forwarding rules + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalForwardingRuleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalForwardingRuleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalForwardingRuleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalForwardingRuleListCall.html) and [*set target*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalForwardingRuleSetTargetCall.html) +* global operations + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalOperationAggregatedListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.GlobalOperationListCall.html) +* [http health checks](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheck.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-compute1/struct.HttpHealthCheckUpdateCall.html) +* [images](http://byron.github.io/google-apis-rs/google-compute1/struct.Image.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.ImageDeleteCall.html), [*deprecate*](http://byron.github.io/google-apis-rs/google-compute1/struct.ImageDeprecateCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.ImageGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.ImageInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.ImageListCall.html) +* [instance templates](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceTemplate.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceTemplateDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceTemplateGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceTemplateInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceTemplateListCall.html) +* [instances](http://byron.github.io/google-apis-rs/google-compute1/struct.Instance.html) + * [*add access config*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceAddAccessConfigCall.html), [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceAggregatedListCall.html), [*attach disk*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceAttachDiskCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceDeleteCall.html), [*delete access config*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceDeleteAccessConfigCall.html), [*detach disk*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceDetachDiskCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceGetCall.html), [*get serial port output*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceGetSerialPortOutputCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceListCall.html), [*reset*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceResetCall.html), [*set disk auto delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceSetDiskAutoDeleteCall.html), [*set metadata*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceSetMetadataCall.html), [*set scheduling*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceSetSchedulingCall.html), [*set tags*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceSetTagCall.html), [*start*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceStartCall.html) and [*stop*](http://byron.github.io/google-apis-rs/google-compute1/struct.InstanceStopCall.html) +* [licenses](http://byron.github.io/google-apis-rs/google-compute1/struct.License.html) + * [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.LicenseGetCall.html) +* [machine types](http://byron.github.io/google-apis-rs/google-compute1/struct.MachineType.html) + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.MachineTypeAggregatedListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.MachineTypeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.MachineTypeListCall.html) +* [networks](http://byron.github.io/google-apis-rs/google-compute1/struct.Network.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.NetworkDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.NetworkGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.NetworkInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.NetworkListCall.html) +* [projects](http://byron.github.io/google-apis-rs/google-compute1/struct.Project.html) + * [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.ProjectGetCall.html), [*move disk*](http://byron.github.io/google-apis-rs/google-compute1/struct.ProjectMoveDiskCall.html), [*move instance*](http://byron.github.io/google-apis-rs/google-compute1/struct.ProjectMoveInstanceCall.html), [*set common instance metadata*](http://byron.github.io/google-apis-rs/google-compute1/struct.ProjectSetCommonInstanceMetadataCall.html) and [*set usage export bucket*](http://byron.github.io/google-apis-rs/google-compute1/struct.ProjectSetUsageExportBucketCall.html) +* region operations + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.RegionOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.RegionOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.RegionOperationListCall.html) +* [regions](http://byron.github.io/google-apis-rs/google-compute1/struct.Region.html) + * [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.RegionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.RegionListCall.html) +* [routes](http://byron.github.io/google-apis-rs/google-compute1/struct.Route.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.RouteDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.RouteGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.RouteInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.RouteListCall.html) +* [snapshots](http://byron.github.io/google-apis-rs/google-compute1/struct.Snapshot.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.SnapshotDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.SnapshotGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.SnapshotListCall.html) +* [target http proxies](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxy.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxyListCall.html) and [*set url map*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetHttpProxySetUrlMapCall.html) +* [target instances](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstance.html) + * [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstanceAggregatedListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstanceDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstanceGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstanceInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetInstanceListCall.html) +* [target pools](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPool.html) + * [*add health check*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolAddHealthCheckCall.html), [*add instance*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolAddInstanceCall.html), [*aggregated list*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolAggregatedListCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolGetCall.html), [*get health*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolGetHealthCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolListCall.html), [*remove health check*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolRemoveHealthCheckCall.html), [*remove instance*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolRemoveInstanceCall.html) and [*set backup*](http://byron.github.io/google-apis-rs/google-compute1/struct.TargetPoolSetBackupCall.html) +* [url maps](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMap.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapPatchCall.html), [*update*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapUpdateCall.html) and [*validate*](http://byron.github.io/google-apis-rs/google-compute1/struct.UrlMapValidateCall.html) +* zone operations + * [*delete*](http://byron.github.io/google-apis-rs/google-compute1/struct.ZoneOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.ZoneOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.ZoneOperationListCall.html) +* [zones](http://byron.github.io/google-apis-rs/google-compute1/struct.Zone.html) + * [*get*](http://byron.github.io/google-apis-rs/google-compute1/struct.ZoneGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-compute1/struct.ZoneListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-compute1/struct.Compute.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-compute1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-compute1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-compute1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.target_instances().delete(...).doit() +let r = hub.instances().stop(...).doit() +let r = hub.target_pools().add_instance(...).doit() +let r = hub.target_pools().add_health_check(...).doit() +let r = hub.target_pools().remove_health_check(...).doit() +let r = hub.backend_services().update(...).doit() +let r = hub.target_pools().delete(...).doit() +let r = hub.firewalls().update(...).doit() +let r = hub.networks().insert(...).doit() +let r = hub.addresses().insert(...).doit() +let r = hub.backend_services().patch(...).doit() +let r = hub.instances().set_tags(...).doit() +let r = hub.instances().set_disk_auto_delete(...).doit() +let r = hub.target_http_proxies().insert(...).doit() +let r = hub.projects().set_usage_export_bucket(...).doit() +let r = hub.url_maps().update(...).doit() +let r = hub.instance_templates().insert(...).doit() +let r = hub.firewalls().patch(...).doit() +let r = hub.firewalls().delete(...).doit() +let r = hub.instances().detach_disk(...).doit() +let r = hub.instances().delete_access_config(...).doit() +let r = hub.backend_services().delete(...).doit() +let r = hub.instances().insert(...).doit() +let r = hub.global_forwarding_rules().set_target(...).doit() +let r = hub.url_maps().insert(...).doit() +let r = hub.instances().add_access_config(...).doit() +let r = hub.region_operations().get(...).doit() +let r = hub.backend_services().insert(...).doit() +let r = hub.disks().insert(...).doit() +let r = hub.instance_templates().delete(...).doit() +let r = hub.global_forwarding_rules().delete(...).doit() +let r = hub.global_forwarding_rules().insert(...).doit() +let r = hub.disks().delete(...).doit() +let r = hub.global_addresses().delete(...).doit() +let r = hub.projects().set_common_instance_metadata(...).doit() +let r = hub.target_pools().insert(...).doit() +let r = hub.target_http_proxies().delete(...).doit() +let r = hub.networks().delete(...).doit() +let r = hub.global_operations().get(...).doit() +let r = hub.url_maps().delete(...).doit() +let r = hub.instances().set_scheduling(...).doit() +let r = hub.instances().attach_disk(...).doit() +let r = hub.addresses().delete(...).doit() +let r = hub.instances().reset(...).doit() +let r = hub.target_http_proxies().set_url_map(...).doit() +let r = hub.disks().create_snapshot(...).doit() +let r = hub.routes().insert(...).doit() +let r = hub.global_addresses().insert(...).doit() +let r = hub.images().deprecate(...).doit() +let r = hub.http_health_checks().patch(...).doit() +let r = hub.http_health_checks().delete(...).doit() +let r = hub.instances().set_metadata(...).doit() +let r = hub.http_health_checks().insert(...).doit() +let r = hub.images().delete(...).doit() +let r = hub.snapshots().delete(...).doit() +let r = hub.forwarding_rules().insert(...).doit() +let r = hub.images().insert(...).doit() +let r = hub.instances().start(...).doit() +let r = hub.target_pools().set_backup(...).doit() +let r = hub.target_instances().insert(...).doit() +let r = hub.forwarding_rules().delete(...).doit() +let r = hub.projects().move_instance(...).doit() +let r = hub.forwarding_rules().set_target(...).doit() +let r = hub.projects().move_disk(...).doit() +let r = hub.firewalls().insert(...).doit() +let r = hub.target_pools().remove_instance(...).doit() +let r = hub.instances().delete(...).doit() +let r = hub.zone_operations().get(...).doit() +let r = hub.http_health_checks().update(...).doit() +let r = hub.routes().delete(...).doit() +let r = hub.url_maps().patch(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-compute1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-compute1" as compute1; +use compute1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use compute1::Compute; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Compute::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.instances().set_disk_auto_delete("project", "zone", "instance", true, "deviceName") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-compute1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-compute1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-compute1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-compute1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-compute1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-compute1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-compute1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-compute1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-compute1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-compute1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-compute1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-compute1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-compute1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **compute1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/compute1/src/cmn.rs b/gen/compute1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/compute1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/compute1/src/lib.rs b/gen/compute1/src/lib.rs new file mode 100644 index 0000000000..e5917ef8cc --- /dev/null +++ b/gen/compute1/src/lib.rs @@ -0,0 +1,42930 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *compute* crate version *0.1.0+20150302*, where *20150302* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *compute* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/compute/docs/reference/latest/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/compute1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Compute.html) ... +//! +//! * addresses +//! * [*aggregated list*](struct.AddresseAggregatedListCall.html), [*delete*](struct.AddresseDeleteCall.html), [*get*](struct.AddresseGetCall.html), [*insert*](struct.AddresseInsertCall.html) and [*list*](struct.AddresseListCall.html) +//! * [backend services](struct.BackendService.html) +//! * [*delete*](struct.BackendServiceDeleteCall.html), [*get*](struct.BackendServiceGetCall.html), [*get health*](struct.BackendServiceGetHealthCall.html), [*insert*](struct.BackendServiceInsertCall.html), [*list*](struct.BackendServiceListCall.html), [*patch*](struct.BackendServicePatchCall.html) and [*update*](struct.BackendServiceUpdateCall.html) +//! * [disk types](struct.DiskType.html) +//! * [*aggregated list*](struct.DiskTypeAggregatedListCall.html), [*get*](struct.DiskTypeGetCall.html) and [*list*](struct.DiskTypeListCall.html) +//! * [disks](struct.Disk.html) +//! * [*aggregated list*](struct.DiskAggregatedListCall.html), [*create snapshot*](struct.DiskCreateSnapshotCall.html), [*delete*](struct.DiskDeleteCall.html), [*get*](struct.DiskGetCall.html), [*insert*](struct.DiskInsertCall.html) and [*list*](struct.DiskListCall.html) +//! * [firewalls](struct.Firewall.html) +//! * [*delete*](struct.FirewallDeleteCall.html), [*get*](struct.FirewallGetCall.html), [*insert*](struct.FirewallInsertCall.html), [*list*](struct.FirewallListCall.html), [*patch*](struct.FirewallPatchCall.html) and [*update*](struct.FirewallUpdateCall.html) +//! * [forwarding rules](struct.ForwardingRule.html) +//! * [*aggregated list*](struct.ForwardingRuleAggregatedListCall.html), [*delete*](struct.ForwardingRuleDeleteCall.html), [*get*](struct.ForwardingRuleGetCall.html), [*insert*](struct.ForwardingRuleInsertCall.html), [*list*](struct.ForwardingRuleListCall.html) and [*set target*](struct.ForwardingRuleSetTargetCall.html) +//! * global addresses +//! * [*delete*](struct.GlobalAddresseDeleteCall.html), [*get*](struct.GlobalAddresseGetCall.html), [*insert*](struct.GlobalAddresseInsertCall.html) and [*list*](struct.GlobalAddresseListCall.html) +//! * global forwarding rules +//! * [*delete*](struct.GlobalForwardingRuleDeleteCall.html), [*get*](struct.GlobalForwardingRuleGetCall.html), [*insert*](struct.GlobalForwardingRuleInsertCall.html), [*list*](struct.GlobalForwardingRuleListCall.html) and [*set target*](struct.GlobalForwardingRuleSetTargetCall.html) +//! * global operations +//! * [*aggregated list*](struct.GlobalOperationAggregatedListCall.html), [*delete*](struct.GlobalOperationDeleteCall.html), [*get*](struct.GlobalOperationGetCall.html) and [*list*](struct.GlobalOperationListCall.html) +//! * [http health checks](struct.HttpHealthCheck.html) +//! * [*delete*](struct.HttpHealthCheckDeleteCall.html), [*get*](struct.HttpHealthCheckGetCall.html), [*insert*](struct.HttpHealthCheckInsertCall.html), [*list*](struct.HttpHealthCheckListCall.html), [*patch*](struct.HttpHealthCheckPatchCall.html) and [*update*](struct.HttpHealthCheckUpdateCall.html) +//! * [images](struct.Image.html) +//! * [*delete*](struct.ImageDeleteCall.html), [*deprecate*](struct.ImageDeprecateCall.html), [*get*](struct.ImageGetCall.html), [*insert*](struct.ImageInsertCall.html) and [*list*](struct.ImageListCall.html) +//! * [instance templates](struct.InstanceTemplate.html) +//! * [*delete*](struct.InstanceTemplateDeleteCall.html), [*get*](struct.InstanceTemplateGetCall.html), [*insert*](struct.InstanceTemplateInsertCall.html) and [*list*](struct.InstanceTemplateListCall.html) +//! * [instances](struct.Instance.html) +//! * [*add access config*](struct.InstanceAddAccessConfigCall.html), [*aggregated list*](struct.InstanceAggregatedListCall.html), [*attach disk*](struct.InstanceAttachDiskCall.html), [*delete*](struct.InstanceDeleteCall.html), [*delete access config*](struct.InstanceDeleteAccessConfigCall.html), [*detach disk*](struct.InstanceDetachDiskCall.html), [*get*](struct.InstanceGetCall.html), [*get serial port output*](struct.InstanceGetSerialPortOutputCall.html), [*insert*](struct.InstanceInsertCall.html), [*list*](struct.InstanceListCall.html), [*reset*](struct.InstanceResetCall.html), [*set disk auto delete*](struct.InstanceSetDiskAutoDeleteCall.html), [*set metadata*](struct.InstanceSetMetadataCall.html), [*set scheduling*](struct.InstanceSetSchedulingCall.html), [*set tags*](struct.InstanceSetTagCall.html), [*start*](struct.InstanceStartCall.html) and [*stop*](struct.InstanceStopCall.html) +//! * [licenses](struct.License.html) +//! * [*get*](struct.LicenseGetCall.html) +//! * [machine types](struct.MachineType.html) +//! * [*aggregated list*](struct.MachineTypeAggregatedListCall.html), [*get*](struct.MachineTypeGetCall.html) and [*list*](struct.MachineTypeListCall.html) +//! * [networks](struct.Network.html) +//! * [*delete*](struct.NetworkDeleteCall.html), [*get*](struct.NetworkGetCall.html), [*insert*](struct.NetworkInsertCall.html) and [*list*](struct.NetworkListCall.html) +//! * [projects](struct.Project.html) +//! * [*get*](struct.ProjectGetCall.html), [*move disk*](struct.ProjectMoveDiskCall.html), [*move instance*](struct.ProjectMoveInstanceCall.html), [*set common instance metadata*](struct.ProjectSetCommonInstanceMetadataCall.html) and [*set usage export bucket*](struct.ProjectSetUsageExportBucketCall.html) +//! * region operations +//! * [*delete*](struct.RegionOperationDeleteCall.html), [*get*](struct.RegionOperationGetCall.html) and [*list*](struct.RegionOperationListCall.html) +//! * [regions](struct.Region.html) +//! * [*get*](struct.RegionGetCall.html) and [*list*](struct.RegionListCall.html) +//! * [routes](struct.Route.html) +//! * [*delete*](struct.RouteDeleteCall.html), [*get*](struct.RouteGetCall.html), [*insert*](struct.RouteInsertCall.html) and [*list*](struct.RouteListCall.html) +//! * [snapshots](struct.Snapshot.html) +//! * [*delete*](struct.SnapshotDeleteCall.html), [*get*](struct.SnapshotGetCall.html) and [*list*](struct.SnapshotListCall.html) +//! * [target http proxies](struct.TargetHttpProxy.html) +//! * [*delete*](struct.TargetHttpProxyDeleteCall.html), [*get*](struct.TargetHttpProxyGetCall.html), [*insert*](struct.TargetHttpProxyInsertCall.html), [*list*](struct.TargetHttpProxyListCall.html) and [*set url map*](struct.TargetHttpProxySetUrlMapCall.html) +//! * [target instances](struct.TargetInstance.html) +//! * [*aggregated list*](struct.TargetInstanceAggregatedListCall.html), [*delete*](struct.TargetInstanceDeleteCall.html), [*get*](struct.TargetInstanceGetCall.html), [*insert*](struct.TargetInstanceInsertCall.html) and [*list*](struct.TargetInstanceListCall.html) +//! * [target pools](struct.TargetPool.html) +//! * [*add health check*](struct.TargetPoolAddHealthCheckCall.html), [*add instance*](struct.TargetPoolAddInstanceCall.html), [*aggregated list*](struct.TargetPoolAggregatedListCall.html), [*delete*](struct.TargetPoolDeleteCall.html), [*get*](struct.TargetPoolGetCall.html), [*get health*](struct.TargetPoolGetHealthCall.html), [*insert*](struct.TargetPoolInsertCall.html), [*list*](struct.TargetPoolListCall.html), [*remove health check*](struct.TargetPoolRemoveHealthCheckCall.html), [*remove instance*](struct.TargetPoolRemoveInstanceCall.html) and [*set backup*](struct.TargetPoolSetBackupCall.html) +//! * [url maps](struct.UrlMap.html) +//! * [*delete*](struct.UrlMapDeleteCall.html), [*get*](struct.UrlMapGetCall.html), [*insert*](struct.UrlMapInsertCall.html), [*list*](struct.UrlMapListCall.html), [*patch*](struct.UrlMapPatchCall.html), [*update*](struct.UrlMapUpdateCall.html) and [*validate*](struct.UrlMapValidateCall.html) +//! * zone operations +//! * [*delete*](struct.ZoneOperationDeleteCall.html), [*get*](struct.ZoneOperationGetCall.html) and [*list*](struct.ZoneOperationListCall.html) +//! * [zones](struct.Zone.html) +//! * [*get*](struct.ZoneGetCall.html) and [*list*](struct.ZoneListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Compute.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.target_instances().delete(...).doit() +//! let r = hub.instances().stop(...).doit() +//! let r = hub.target_pools().add_instance(...).doit() +//! let r = hub.target_pools().add_health_check(...).doit() +//! let r = hub.target_pools().remove_health_check(...).doit() +//! let r = hub.backend_services().update(...).doit() +//! let r = hub.target_pools().delete(...).doit() +//! let r = hub.firewalls().update(...).doit() +//! let r = hub.networks().insert(...).doit() +//! let r = hub.addresses().insert(...).doit() +//! let r = hub.backend_services().patch(...).doit() +//! let r = hub.instances().set_tags(...).doit() +//! let r = hub.instances().set_disk_auto_delete(...).doit() +//! let r = hub.target_http_proxies().insert(...).doit() +//! let r = hub.projects().set_usage_export_bucket(...).doit() +//! let r = hub.url_maps().update(...).doit() +//! let r = hub.instance_templates().insert(...).doit() +//! let r = hub.firewalls().patch(...).doit() +//! let r = hub.firewalls().delete(...).doit() +//! let r = hub.instances().detach_disk(...).doit() +//! let r = hub.instances().delete_access_config(...).doit() +//! let r = hub.backend_services().delete(...).doit() +//! let r = hub.instances().insert(...).doit() +//! let r = hub.global_forwarding_rules().set_target(...).doit() +//! let r = hub.url_maps().insert(...).doit() +//! let r = hub.instances().add_access_config(...).doit() +//! let r = hub.region_operations().get(...).doit() +//! let r = hub.backend_services().insert(...).doit() +//! let r = hub.disks().insert(...).doit() +//! let r = hub.instance_templates().delete(...).doit() +//! let r = hub.global_forwarding_rules().delete(...).doit() +//! let r = hub.global_forwarding_rules().insert(...).doit() +//! let r = hub.disks().delete(...).doit() +//! let r = hub.global_addresses().delete(...).doit() +//! let r = hub.projects().set_common_instance_metadata(...).doit() +//! let r = hub.target_pools().insert(...).doit() +//! let r = hub.target_http_proxies().delete(...).doit() +//! let r = hub.networks().delete(...).doit() +//! let r = hub.global_operations().get(...).doit() +//! let r = hub.url_maps().delete(...).doit() +//! let r = hub.instances().set_scheduling(...).doit() +//! let r = hub.instances().attach_disk(...).doit() +//! let r = hub.addresses().delete(...).doit() +//! let r = hub.instances().reset(...).doit() +//! let r = hub.target_http_proxies().set_url_map(...).doit() +//! let r = hub.disks().create_snapshot(...).doit() +//! let r = hub.routes().insert(...).doit() +//! let r = hub.global_addresses().insert(...).doit() +//! let r = hub.images().deprecate(...).doit() +//! let r = hub.http_health_checks().patch(...).doit() +//! let r = hub.http_health_checks().delete(...).doit() +//! let r = hub.instances().set_metadata(...).doit() +//! let r = hub.http_health_checks().insert(...).doit() +//! let r = hub.images().delete(...).doit() +//! let r = hub.snapshots().delete(...).doit() +//! let r = hub.forwarding_rules().insert(...).doit() +//! let r = hub.images().insert(...).doit() +//! let r = hub.instances().start(...).doit() +//! let r = hub.target_pools().set_backup(...).doit() +//! let r = hub.target_instances().insert(...).doit() +//! let r = hub.forwarding_rules().delete(...).doit() +//! let r = hub.projects().move_instance(...).doit() +//! let r = hub.forwarding_rules().set_target(...).doit() +//! let r = hub.projects().move_disk(...).doit() +//! let r = hub.firewalls().insert(...).doit() +//! let r = hub.target_pools().remove_instance(...).doit() +//! let r = hub.instances().delete(...).doit() +//! let r = hub.zone_operations().get(...).doit() +//! let r = hub.http_health_checks().update(...).doit() +//! let r = hub.routes().delete(...).doit() +//! let r = hub.url_maps().patch(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-compute1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-compute1" as compute1; +//! use compute1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use compute1::Compute; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Compute::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.instances().set_disk_auto_delete("project", "zone", "instance", true, "deviceName") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your Google Compute Engine resources + Full, + + /// Manage your data and permissions in Google Cloud Storage + DevstorageFullControl, + + /// View your data in Google Cloud Storage + DevstorageReadOnly, + + /// Manage your data in Google Cloud Storage + DevstorageReadWrite, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, + + /// View your Google Compute Engine resources + Readonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/compute", + Scope::DevstorageFullControl => "https://www.googleapis.com/auth/devstorage.full_control", + Scope::DevstorageReadOnly => "https://www.googleapis.com/auth/devstorage.read_only", + Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::Readonly => "https://www.googleapis.com/auth/compute.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Compute related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// use compute1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().set_disk_auto_delete("project", "zone", "instance", true, "deviceName") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Compute { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Compute {} + +impl<'a, C, NC, A> Compute + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Compute { + Compute { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn addresses(&'a self) -> AddresseMethods<'a, C, NC, A> { + AddresseMethods { hub: &self } + } + pub fn backend_services(&'a self) -> BackendServiceMethods<'a, C, NC, A> { + BackendServiceMethods { hub: &self } + } + pub fn disk_types(&'a self) -> DiskTypeMethods<'a, C, NC, A> { + DiskTypeMethods { hub: &self } + } + pub fn disks(&'a self) -> DiskMethods<'a, C, NC, A> { + DiskMethods { hub: &self } + } + pub fn firewalls(&'a self) -> FirewallMethods<'a, C, NC, A> { + FirewallMethods { hub: &self } + } + pub fn forwarding_rules(&'a self) -> ForwardingRuleMethods<'a, C, NC, A> { + ForwardingRuleMethods { hub: &self } + } + pub fn global_addresses(&'a self) -> GlobalAddresseMethods<'a, C, NC, A> { + GlobalAddresseMethods { hub: &self } + } + pub fn global_forwarding_rules(&'a self) -> GlobalForwardingRuleMethods<'a, C, NC, A> { + GlobalForwardingRuleMethods { hub: &self } + } + pub fn global_operations(&'a self) -> GlobalOperationMethods<'a, C, NC, A> { + GlobalOperationMethods { hub: &self } + } + pub fn http_health_checks(&'a self) -> HttpHealthCheckMethods<'a, C, NC, A> { + HttpHealthCheckMethods { hub: &self } + } + pub fn images(&'a self) -> ImageMethods<'a, C, NC, A> { + ImageMethods { hub: &self } + } + pub fn instance_templates(&'a self) -> InstanceTemplateMethods<'a, C, NC, A> { + InstanceTemplateMethods { hub: &self } + } + pub fn instances(&'a self) -> InstanceMethods<'a, C, NC, A> { + InstanceMethods { hub: &self } + } + pub fn licenses(&'a self) -> LicenseMethods<'a, C, NC, A> { + LicenseMethods { hub: &self } + } + pub fn machine_types(&'a self) -> MachineTypeMethods<'a, C, NC, A> { + MachineTypeMethods { hub: &self } + } + pub fn networks(&'a self) -> NetworkMethods<'a, C, NC, A> { + NetworkMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, NC, A> { + ProjectMethods { hub: &self } + } + pub fn region_operations(&'a self) -> RegionOperationMethods<'a, C, NC, A> { + RegionOperationMethods { hub: &self } + } + pub fn regions(&'a self) -> RegionMethods<'a, C, NC, A> { + RegionMethods { hub: &self } + } + pub fn routes(&'a self) -> RouteMethods<'a, C, NC, A> { + RouteMethods { hub: &self } + } + pub fn snapshots(&'a self) -> SnapshotMethods<'a, C, NC, A> { + SnapshotMethods { hub: &self } + } + pub fn target_http_proxies(&'a self) -> TargetHttpProxyMethods<'a, C, NC, A> { + TargetHttpProxyMethods { hub: &self } + } + pub fn target_instances(&'a self) -> TargetInstanceMethods<'a, C, NC, A> { + TargetInstanceMethods { hub: &self } + } + pub fn target_pools(&'a self) -> TargetPoolMethods<'a, C, NC, A> { + TargetPoolMethods { hub: &self } + } + pub fn url_maps(&'a self) -> UrlMapMethods<'a, C, NC, A> { + UrlMapMethods { hub: &self } + } + pub fn zone_operations(&'a self) -> ZoneOperationMethods<'a, C, NC, A> { + ZoneOperationMethods { hub: &self } + } + pub fn zones(&'a self) -> ZoneMethods<'a, C, NC, A> { + ZoneMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// An instance's serial console output. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get serial port output instances](struct.InstanceGetSerialPortOutputCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SerialPortOutput { + /// [Output Only] Type of the resource. Always compute#serialPortOutput for serial port output. + pub kind: String, + /// [Output Only] The contents of the console output. + pub contents: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for SerialPortOutput {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationsScopedList { + /// [Output Only] List of operations contained in this scope. + pub operations: Vec, + /// [Output Only] Informational warning which replaces the list of operations when the list is empty. + pub warning: OperationsScopedListWarning, +} + +impl Part for OperationsScopedList {} + + +/// Contains a list of UrlMap resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list url maps](struct.UrlMapListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlMapList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of UrlMap resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for UrlMapList {} + + +/// [Output Only] Informational warning which replaces the list of instances when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstancesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for InstancesScopedListWarning {} +impl Part for InstancesScopedListWarning {} + + +/// A disk type resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list disk types](struct.DiskTypeAggregatedListCall.html) (none) +/// * [list disk types](struct.DiskTypeListCall.html) (none) +/// * [get disk types](struct.DiskTypeGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskType { + /// [Output Only] Type of the resource. Always compute#diskType for disk types. + pub kind: String, + /// [Output Only] An optional textual description of the resource. + pub description: String, + /// [Output Only] URL of the zone where the disk type resides. + pub zone: String, + /// [Output Only] An optional textual description of the valid disk size, such as "10GB-10TB". + #[serde(alias="validDiskSize")] + pub valid_disk_size: String, + /// [Output Only] The deprecation status associated with this disk type. + pub deprecated: DeprecationStatus, + /// [Output Only] Server defined default disk size in GB. + #[serde(alias="defaultDiskSizeGb")] + pub default_disk_size_gb: String, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Name of the resource. + pub name: String, +} + +impl Resource for DiskType {} +impl ResponseResult for DiskType {} + + +/// An Instance resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get serial port output instances](struct.InstanceGetSerialPortOutputCall.html) (none) +/// * [attach disk instances](struct.InstanceAttachDiskCall.html) (none) +/// * [insert instances](struct.InstanceInsertCall.html) (request) +/// * [stop instances](struct.InstanceStopCall.html) (none) +/// * [set metadata instances](struct.InstanceSetMetadataCall.html) (none) +/// * [start instances](struct.InstanceStartCall.html) (none) +/// * [detach disk instances](struct.InstanceDetachDiskCall.html) (none) +/// * [delete access config instances](struct.InstanceDeleteAccessConfigCall.html) (none) +/// * [get instances](struct.InstanceGetCall.html) (response) +/// * [set tags instances](struct.InstanceSetTagCall.html) (none) +/// * [set scheduling instances](struct.InstanceSetSchedulingCall.html) (none) +/// * [list instances](struct.InstanceListCall.html) (none) +/// * [delete instances](struct.InstanceDeleteCall.html) (none) +/// * [reset instances](struct.InstanceResetCall.html) (none) +/// * [aggregated list instances](struct.InstanceAggregatedListCall.html) (none) +/// * [add access config instances](struct.InstanceAddAccessConfigCall.html) (none) +/// * [set disk auto delete instances](struct.InstanceSetDiskAutoDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Instance { + /// [Output Only] The status of the instance. One of the following values: PROVISIONING, STAGING, RUNNING, STOPPING, STOPPED, TERMINATED. + pub status: Option, + /// Full or partial URL of the machine type resource to use for this instance. This is provided by the client when the instance is created. For example, the following is a valid partial url: + /// + /// zones/zone/machineTypes/machine-type + #[serde(alias="machineType")] + pub machine_type: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// A list of tags to appy to this instance. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during instance creation. The tags can be later modified by the setTags method. Each tag within the list must comply with RFC1035. + pub tags: Option, + /// Scheduling options for this instance. + pub scheduling: Option, + /// Allows this instance to send and receive packets with non-matching destination or source IPs. This is required if you plan to use this instance to forward routes. For more information, see Enabling IP Forwarding. + #[serde(alias="canIpForward")] + pub can_ip_forward: Option, + /// A list of service accounts, with their specified scopes, authorized for this instance. Service accounts generate access tokens that can be accessed through the metadata server and used to authenticate applications on the instance. See Authenticating from Google Compute Engine for more information. + #[serde(alias="serviceAccounts")] + pub service_accounts: Option>, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// An array of configurations for this interface. This specifies how this interface is configured to interact with other network services, such as connecting to the internet. + #[serde(alias="networkInterfaces")] + pub network_interfaces: Option>, + /// [Output Only] Type of the resource. Always compute#instance for instances. + pub kind: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, + /// [Output Only] URL of the zone where the instance resides. + pub zone: Option, + /// Array of disks associated with this instance. Persistent disks must be created before you can assign them. + pub disks: Option>, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// [Output Only] An optional, human-readable explanation of the status. + #[serde(alias="statusMessage")] + pub status_message: Option, + /// The metadata key/value pairs assigned to this instance. This includes custom metadata and predefined keys. + pub metadata: Option, +} + +impl RequestValue for Instance {} +impl Resource for Instance {} +impl ResponseResult for Instance {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypesScopedList { + /// [Output Only] List of machine types contained in this scope. + #[serde(alias="machineTypes")] + pub machine_types: Vec, + /// [Output Only] An informational warning that appears when the machine types list is empty. + pub warning: MachineTypesScopedListWarning, +} + +impl Part for MachineTypesScopedList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [add instance target pools](struct.TargetPoolAddInstanceCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TargetPoolsAddInstanceRequest { + /// URLs of the instances to be added to targetPool. + pub instances: Option>, +} + +impl RequestValue for TargetPoolsAddInstanceRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list global operations](struct.GlobalOperationAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped operation lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#operationAggregatedList for aggregated lists of operations. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for OperationAggregatedList {} + + +/// Contains a list of Image resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list images](struct.ImageListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ImageList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of Image resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ImageList {} + + +/// A metadata key/value entry. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set common instance metadata projects](struct.ProjectSetCommonInstanceMetadataCall.html) (request) +/// * [set metadata instances](struct.InstanceSetMetadataCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Metadata { + /// Array of key/value pairs. The total size of all keys and values must be less than 512 KB. + pub items: Option>, + /// [Output Only] Type of the resource. Always compute#metadata for metadata. + pub kind: Option, + /// Specifies a fingerprint for this request, which is essentially a hash of the metadata's contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata. + pub fingerprint: Option, +} + +impl RequestValue for Metadata {} + + +/// [Output Only] Informational warning which replaces the list of disk types when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskTypesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for DiskTypesScopedListWarning {} +impl Part for DiskTypesScopedListWarning {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ForwardingRulesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for ForwardingRulesScopedListWarningData {} +impl Part for ForwardingRulesScopedListWarningData {} + + +/// A set of instance tags. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set tags instances](struct.InstanceSetTagCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Tags { + /// An array of tags. Each tag must be 1-63 characters long, and comply with RFC1035. + pub items: Option>, + /// Specifies a fingerprint for this request, which is essentially a hash of the metadata's contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata. + /// + /// To see the latest fingerprint, make get() request to the instance. + pub fingerprint: Option, +} + +impl RequestValue for Tags {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [validate url maps](struct.UrlMapValidateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UrlMapsValidateRequest { + /// Content of the UrlMap to be validated. + pub resource: Option, +} + +impl RequestValue for UrlMapsValidateRequest {} + + +/// A TargetHttpProxy resource. This resource defines an HTTP proxy. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get target http proxies](struct.TargetHttpProxyGetCall.html) (response) +/// * [insert target http proxies](struct.TargetHttpProxyInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetHttpProxy { + /// Type of the resource. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// URL to the UrlMap resource that defines the mapping from URL to the BackendService. + #[serde(alias="urlMap")] + pub url_map: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for TargetHttpProxy {} +impl ResponseResult for TargetHttpProxy {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list disks](struct.DiskAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped disk lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#diskAggregatedList for aggregated lists of persistent disks. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for DiskAggregatedList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AddressesScopedList { + /// [Output Only] Informational warning which replaces the list of addresses when the list is empty. + pub warning: AddressesScopedListWarning, + /// [Output Only] List of addresses contained in this scope. + pub addresses: Vec
, +} + +impl Part for AddressesScopedList {} + + +/// Array of key/value pairs. The total size of all keys and values must be less than 512 KB. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MetadataItems { + /// Key for the metadata entry. Keys must conform to the following regexp: [a-zA-Z0-9-_]+, and be less than 128 bytes in length. This is reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project. + pub key: String, + /// Value for the metadata entry. These are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on values is that their size must be less than or equal to 32768 bytes. + pub value: String, +} + +impl NestedType for MetadataItems {} +impl Part for MetadataItems {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstancesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for InstancesScopedListWarningData {} +impl Part for InstancesScopedListWarningData {} + + +/// Contains a list of address resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list addresses](struct.AddresseListCall.html) (response) +/// * [list global addresses](struct.GlobalAddresseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AddressList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Address resources. + pub items: Vec
, + /// [Output Only] Type of resource. Always compute#addressList for lists of addresses. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for AddressList {} + + +/// Contains a list of disk type resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list disk types](struct.DiskTypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskTypeList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Disk Type resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#diskTypeList for disk types. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for DiskTypeList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list addresses](struct.AddresseAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AddressAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped address lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#addressAggregatedList for aggregated lists of addresses. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for AddressAggregatedList {} + + +/// Message representing the validation result for a UrlMap. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlMapValidationResult { + /// no description provided + #[serde(alias="testFailures")] + pub test_failures: Vec, + /// no description provided + #[serde(alias="loadErrors")] + pub load_errors: Vec, + /// Whether the given UrlMap can be successfully loaded. If false, 'loadErrors' indicates the reasons. + #[serde(alias="loadSucceeded")] + pub load_succeeded: bool, + /// If successfully loaded, this field indicates whether the test passed. If false, 'testFailures's indicate the reason of failure. + #[serde(alias="testPassed")] + pub test_passed: bool, +} + +impl Part for UrlMapValidationResult {} + + +/// Informational warning which replaces the list of addresses when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolsScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for TargetPoolsScopedListWarning {} +impl Part for TargetPoolsScopedListWarning {} + + +/// A matcher for the path portion of the URL. The BackendService from the longest-matched rule will serve the URL. If no rule was matched, the default_service will be used. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PathMatcher { + /// The URL to the BackendService resource. This will be used if none of the 'pathRules' defined by this PathMatcher is met by the URL's path portion. + #[serde(alias="defaultService")] + pub default_service: String, + /// The list of path rules. + #[serde(alias="pathRules")] + pub path_rules: Vec, + /// no description provided + pub description: String, + /// The name to which this PathMatcher is referred by the HostRule. + pub name: String, +} + +impl Part for PathMatcher {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetInstancesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for TargetInstancesScopedListWarningData {} +impl Part for TargetInstancesScopedListWarningData {} + + +/// Contains a list of persistent disk snapshot resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list snapshots](struct.SnapshotListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SnapshotList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of Snapshot resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for SnapshotList {} + + +/// Region resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list regions](struct.RegionListCall.html) (none) +/// * [get regions](struct.RegionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Region { + /// [Output Only] Status of the region, either UP or DOWN. + pub status: String, + /// [Output Only] Type of the resource. Always compute#region for regions. + pub kind: String, + /// [Output Only] Textual description of the resource. + pub description: String, + /// [Output Only] The deprecation status associated with this region. + pub deprecated: DeprecationStatus, + /// [Output Only] Quotas assigned to this region. + pub quotas: Vec, + /// [Output Only] A list of zones available in this region, in the form of resource URLs. + pub zones: Vec, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server . + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Name of the resource. + pub name: String, +} + +impl Resource for Region {} +impl ResponseResult for Region {} + + +/// A path-matching rule for a URL. If matched, will use the specified BackendService to handle the traffic arriving at this URL. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PathRule { + /// The list of path patterns to match. Each must start with / and the only place a * is allowed is at the end following a /. The string fed to the path matcher does not include any text after the first ? or #, and those chars are not allowed here. + pub paths: Vec, + /// The URL of the BackendService resource if this rule is matched. + pub service: String, +} + +impl Part for PathRule {} + + +/// A service account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ServiceAccount { + /// The list of scopes to be made available for this service account. + pub scopes: Vec, + /// Email address of the service account. + pub email: String, +} + +impl Part for ServiceAccount {} + + +/// A Project resource. Projects can only be created in the Google Developers Console. Unless marked otherwise, values can only be modified in the console. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set common instance metadata projects](struct.ProjectSetCommonInstanceMetadataCall.html) (none) +/// * [set usage export bucket projects](struct.ProjectSetUsageExportBucketCall.html) (none) +/// * [move instance projects](struct.ProjectMoveInstanceCall.html) (none) +/// * [get projects](struct.ProjectGetCall.html) (response) +/// * [move disk projects](struct.ProjectMoveDiskCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Project { + /// [Output Only] Type of the resource. Always compute#project for projects. + pub kind: String, + /// An optional textual description of the resource. + pub description: String, + /// Metadata key/value pairs available to all instances contained in this project. See Custom metadata for more information. + #[serde(alias="commonInstanceMetadata")] + pub common_instance_metadata: Metadata, + /// [Output Only] Quotas assigned to this project. + pub quotas: Vec, + /// The location in Cloud Storage and naming method of the daily usage report. + #[serde(alias="usageExportLocation")] + pub usage_export_location: UsageExportLocation, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// Name of the resource. + pub name: String, +} + +impl Resource for Project {} +impl ResponseResult for Project {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for MachineTypesScopedListWarningData {} +impl Part for MachineTypesScopedListWarningData {} + + +/// A persistent disk snapshot resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list snapshots](struct.SnapshotListCall.html) (none) +/// * [create snapshot disks](struct.DiskCreateSnapshotCall.html) (request) +/// * [delete snapshots](struct.SnapshotDeleteCall.html) (none) +/// * [get snapshots](struct.SnapshotGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Snapshot { + /// The status of the persistent disk snapshot (output only). + pub status: Option, + /// Type of the resource. + pub kind: Option, + /// A size of the the storage used by the snapshot. As snapshots share storage this number is expected to change with snapshot creation/deletion. + #[serde(alias="storageBytes")] + pub storage_bytes: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// The source disk used to create this snapshot. + #[serde(alias="sourceDisk")] + pub source_disk: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// The 'id' value of the disk used to create this snapshot. This value may be used to determine whether the snapshot was taken from the current or a previous instance of a given disk name. + #[serde(alias="sourceDiskId")] + pub source_disk_id: Option, + /// Size of the persistent disk snapshot, specified in GB (output only). + #[serde(alias="diskSizeGb")] + pub disk_size_gb: Option, + /// Public visible licenses. + pub licenses: Option>, + /// An indicator whether storageBytes is in a stable state, or it is being adjusted as a result of shared storage reallocation. + #[serde(alias="storageBytesStatus")] + pub storage_bytes_status: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for Snapshot {} +impl Resource for Snapshot {} +impl ResponseResult for Snapshot {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskTypesScopedList { + /// [Output Only] Informational warning which replaces the list of disk types when the list is empty. + pub warning: DiskTypesScopedListWarning, + /// [Output Only] List of disk types contained in this scope. + #[serde(alias="diskTypes")] + pub disk_types: Vec, +} + +impl Part for DiskTypesScopedList {} + + +/// A BackendService resource. This resource defines a group of backend VMs together with their serving capacity. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get backend services](struct.BackendServiceGetCall.html) (response) +/// * [insert backend services](struct.BackendServiceInsertCall.html) (request) +/// * [list backend services](struct.BackendServiceListCall.html) (none) +/// * [update backend services](struct.BackendServiceUpdateCall.html) (request) +/// * [get health backend services](struct.BackendServiceGetHealthCall.html) (none) +/// * [delete backend services](struct.BackendServiceDeleteCall.html) (none) +/// * [patch backend services](struct.BackendServicePatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BackendService { + /// Type of the resource. + pub kind: Option, + /// no description provided + pub protocol: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. + #[serde(alias="timeoutSec")] + pub timeout_sec: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// The list of backends that serve this BackendService. + pub backends: Option>, + /// Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-date fingerprint must be provided in order to update the BackendService. + pub fingerprint: Option, + /// Name of backend port. The same name should appear in the resource views referenced by this service. Required. + #[serde(alias="portName")] + pub port_name: Option, + /// The list of URLs to the HttpHealthCheck resource for health checking this BackendService. Currently at most one health check can be specified, and a health check is required. + #[serde(alias="healthChecks")] + pub health_checks: Option>, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Deprecated in favor of port_name. The TCP port to connect on the backend. The default value is 80. + pub port: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for BackendService {} +impl Resource for BackendService {} +impl ResponseResult for BackendService {} + + +/// A host-matching rule for a URL. If matched, will use the named PathMatcher to select the BackendService. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HostRule { + /// The list of host patterns to match. They must be valid hostnames except that they may start with *. or *-. The * acts like a glob and will match any string of atoms (separated by .s and -s) to the left. + pub hosts: Vec, + /// no description provided + pub description: String, + /// The name of the PathMatcher to match the path portion of the URL, if the this HostRule matches the URL's host portion. + #[serde(alias="pathMatcher")] + pub path_matcher: String, +} + +impl Part for HostRule {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get health backend services](struct.BackendServiceGetHealthCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ResourceGroupReference { + /// A URI referencing one of the resource views listed in the backend service. + pub group: Option, +} + +impl RequestValue for ResourceGroupReference {} + + +/// Contains a list of Machine Type resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list machine types](struct.MachineTypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypeList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Machine Type resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#machineTypeList for lists of machine types. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for MachineTypeList {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DisksScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for DisksScopedListWarningData {} +impl Part for DisksScopedListWarningData {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarningsData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// Contains a list of ForwardingRule resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list global forwarding rules](struct.GlobalForwardingRuleListCall.html) (response) +/// * [list forwarding rules](struct.ForwardingRuleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ForwardingRuleList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of ForwardingRule resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ForwardingRuleList {} + + +/// Informational warning which replaces the list of forwarding rules when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ForwardingRulesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for ForwardingRulesScopedListWarning {} +impl Part for ForwardingRulesScopedListWarning {} + + +/// Contains a list of Firewall resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list firewalls](struct.FirewallListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FirewallList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Firewall resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#firewallList for lists of firewalls. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for FirewallList {} + + +/// Message for the expected URL mappings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UrlMapTest { + /// Path portion of the URL. + pub path: String, + /// Host portion of the URL. + pub host: String, + /// Description of this test case. + pub description: String, + /// Expected BackendService resource the given URL should be mapped to. + pub service: String, +} + +impl Part for UrlMapTest {} + + +/// A Firewall resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch firewalls](struct.FirewallPatchCall.html) (request) +/// * [list firewalls](struct.FirewallListCall.html) (none) +/// * [get firewalls](struct.FirewallGetCall.html) (response) +/// * [update firewalls](struct.FirewallUpdateCall.html) (request) +/// * [delete firewalls](struct.FirewallDeleteCall.html) (none) +/// * [insert firewalls](struct.FirewallInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Firewall { + /// [Output Ony] Type of the resource. Always compute#firewall for firewall rules. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// A list of instance tags which this rule applies to. One or both of sourceRanges and sourceTags may be set. + /// + /// If both properties are set, an inbound connection is allowed if the range or the tag of the source matches the sourceRanges OR matches the sourceTags property; the connection does not need to match both properties. + #[serde(alias="sourceTags")] + pub source_tags: Option>, + /// The IP address blocks that this rule applies to, expressed in CIDR format. One or both of sourceRanges and sourceTags may be set. + /// + /// If both properties are set, an inbound connection is allowed if the range or the tag of the source matches the sourceRanges OR matches the sourceTags property; the connection does not need to match both properties. + #[serde(alias="sourceRanges")] + pub source_ranges: Option>, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, + /// A list of instance tags indicating sets of instances located on network which may make network connections as specified in allowed[]. If no targetTags are specified, the firewall rule applies to all instances on the specified network. + #[serde(alias="targetTags")] + pub target_tags: Option>, + /// The list of rules specified by this firewall. Each rule specifies a protocol and port-range tuple that describes a permitted connection. + pub allowed: Option>, + /// [Output Only] Creation timestamp in RFC3339text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// URL of the network resource for this firewall rule. This field is required for creating an instance but optional when creating a firewall rule. If not specified when creating a firewall rule, the default network is used: + /// global/networks/default + /// If you choose to specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: + /// - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network + /// - projects/myproject/global/networks/my-network + /// - global/networks/default + pub network: Option, +} + +impl RequestValue for Firewall {} +impl Resource for Firewall {} +impl ResponseResult for Firewall {} + + +/// [Output Only] If warning messages are generated during processing of the operation, this field will be populated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for OperationWarnings {} +impl Part for OperationWarnings {} + + +/// Contains a list of operation resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list region operations](struct.RegionOperationListCall.html) (response) +/// * [list zone operations](struct.ZoneOperationListCall.html) (response) +/// * [list global operations](struct.GlobalOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationList { + /// [Output Only] A token used to continue a truncate. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] The operation resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#operations for Operations resource. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for OperationList {} + + +/// A TargetInstance resource. This resource defines an endpoint VM that terminates traffic of certain protocols. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete target instances](struct.TargetInstanceDeleteCall.html) (none) +/// * [aggregated list target instances](struct.TargetInstanceAggregatedListCall.html) (none) +/// * [get target instances](struct.TargetInstanceGetCall.html) (response) +/// * [list target instances](struct.TargetInstanceListCall.html) (none) +/// * [insert target instances](struct.TargetInstanceInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetInstance { + /// NAT option controlling how IPs are NAT'ed to the VM. Currently only NO_NAT (default value) is supported. + #[serde(alias="natPolicy")] + pub nat_policy: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// URL of the zone where the target instance resides (output only). + pub zone: Option, + /// Type of the resource. + pub kind: Option, + /// The URL to the instance that terminates the relevant traffic. + pub instance: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for TargetInstance {} +impl Resource for TargetInstance {} +impl ResponseResult for TargetInstance {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list target instances](struct.TargetInstanceAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetInstanceAggregatedList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A map of scoped target instance lists. + pub items: HashMap, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for TargetInstanceAggregatedList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list disk types](struct.DiskTypeAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskTypeAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped disk type lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#diskTypeAggregatedList. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for DiskTypeAggregatedList {} + + +/// An Instance Template resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list instance templates](struct.InstanceTemplateListCall.html) (none) +/// * [delete instance templates](struct.InstanceTemplateDeleteCall.html) (none) +/// * [insert instance templates](struct.InstanceTemplateInsertCall.html) (request) +/// * [get instance templates](struct.InstanceTemplateGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InstanceTemplate { + /// Type of the resource. + pub kind: Option, + /// An optional textual description of the instance template resource; provided by the client when the resource is created. + pub description: Option, + /// Name of the instance template resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035 + pub name: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// The instance properties portion of this instance template resource. + pub properties: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, +} + +impl RequestValue for InstanceTemplate {} +impl Resource for InstanceTemplate {} +impl ResponseResult for InstanceTemplate {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct HealthStatus { + /// URL of the instance resource. + pub instance: String, + /// Health state of the instance. + #[serde(alias="healthState")] + pub health_state: String, + /// The IP address represented by this resource. + #[serde(alias="ipAddress")] + pub ip_address: String, + /// The port on the instance. + pub port: i32, +} + +impl Part for HealthStatus {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list machine types](struct.MachineTypeAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypeAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped machine type lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#machineTypeAggregatedList for aggregated lists of machine types. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for MachineTypeAggregatedList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [validate url maps](struct.UrlMapValidateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UrlMapsValidateResponse { + /// no description provided + pub result: UrlMapValidationResult, +} + +impl ResponseResult for UrlMapsValidateResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ForwardingRulesScopedList { + /// List of forwarding rules contained in this scope. + #[serde(alias="forwardingRules")] + pub forwarding_rules: Vec, + /// Informational warning which replaces the list of forwarding rules when the list is empty. + pub warning: ForwardingRulesScopedListWarning, +} + +impl Part for ForwardingRulesScopedList {} + + +/// An operation resource, used to manage asynchronous API requests. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete target instances](struct.TargetInstanceDeleteCall.html) (response) +/// * [stop instances](struct.InstanceStopCall.html) (response) +/// * [add instance target pools](struct.TargetPoolAddInstanceCall.html) (response) +/// * [add health check target pools](struct.TargetPoolAddHealthCheckCall.html) (response) +/// * [remove health check target pools](struct.TargetPoolRemoveHealthCheckCall.html) (response) +/// * [update backend services](struct.BackendServiceUpdateCall.html) (response) +/// * [delete target pools](struct.TargetPoolDeleteCall.html) (response) +/// * [update firewalls](struct.FirewallUpdateCall.html) (response) +/// * [insert networks](struct.NetworkInsertCall.html) (response) +/// * [insert addresses](struct.AddresseInsertCall.html) (response) +/// * [patch backend services](struct.BackendServicePatchCall.html) (response) +/// * [set tags instances](struct.InstanceSetTagCall.html) (response) +/// * [set disk auto delete instances](struct.InstanceSetDiskAutoDeleteCall.html) (response) +/// * [insert target http proxies](struct.TargetHttpProxyInsertCall.html) (response) +/// * [set usage export bucket projects](struct.ProjectSetUsageExportBucketCall.html) (response) +/// * [update url maps](struct.UrlMapUpdateCall.html) (response) +/// * [insert instance templates](struct.InstanceTemplateInsertCall.html) (response) +/// * [patch firewalls](struct.FirewallPatchCall.html) (response) +/// * [delete firewalls](struct.FirewallDeleteCall.html) (response) +/// * [detach disk instances](struct.InstanceDetachDiskCall.html) (response) +/// * [delete access config instances](struct.InstanceDeleteAccessConfigCall.html) (response) +/// * [delete backend services](struct.BackendServiceDeleteCall.html) (response) +/// * [insert instances](struct.InstanceInsertCall.html) (response) +/// * [set target global forwarding rules](struct.GlobalForwardingRuleSetTargetCall.html) (response) +/// * [insert url maps](struct.UrlMapInsertCall.html) (response) +/// * [add access config instances](struct.InstanceAddAccessConfigCall.html) (response) +/// * [get region operations](struct.RegionOperationGetCall.html) (response) +/// * [insert backend services](struct.BackendServiceInsertCall.html) (response) +/// * [insert disks](struct.DiskInsertCall.html) (response) +/// * [delete instance templates](struct.InstanceTemplateDeleteCall.html) (response) +/// * [delete global forwarding rules](struct.GlobalForwardingRuleDeleteCall.html) (response) +/// * [insert global forwarding rules](struct.GlobalForwardingRuleInsertCall.html) (response) +/// * [delete disks](struct.DiskDeleteCall.html) (response) +/// * [delete global addresses](struct.GlobalAddresseDeleteCall.html) (response) +/// * [set common instance metadata projects](struct.ProjectSetCommonInstanceMetadataCall.html) (response) +/// * [insert target pools](struct.TargetPoolInsertCall.html) (response) +/// * [delete target http proxies](struct.TargetHttpProxyDeleteCall.html) (response) +/// * [delete networks](struct.NetworkDeleteCall.html) (response) +/// * [get global operations](struct.GlobalOperationGetCall.html) (response) +/// * [delete url maps](struct.UrlMapDeleteCall.html) (response) +/// * [set scheduling instances](struct.InstanceSetSchedulingCall.html) (response) +/// * [attach disk instances](struct.InstanceAttachDiskCall.html) (response) +/// * [delete addresses](struct.AddresseDeleteCall.html) (response) +/// * [reset instances](struct.InstanceResetCall.html) (response) +/// * [set url map target http proxies](struct.TargetHttpProxySetUrlMapCall.html) (response) +/// * [create snapshot disks](struct.DiskCreateSnapshotCall.html) (response) +/// * [insert routes](struct.RouteInsertCall.html) (response) +/// * [insert global addresses](struct.GlobalAddresseInsertCall.html) (response) +/// * [deprecate images](struct.ImageDeprecateCall.html) (response) +/// * [patch http health checks](struct.HttpHealthCheckPatchCall.html) (response) +/// * [delete http health checks](struct.HttpHealthCheckDeleteCall.html) (response) +/// * [set metadata instances](struct.InstanceSetMetadataCall.html) (response) +/// * [insert http health checks](struct.HttpHealthCheckInsertCall.html) (response) +/// * [delete images](struct.ImageDeleteCall.html) (response) +/// * [delete snapshots](struct.SnapshotDeleteCall.html) (response) +/// * [insert forwarding rules](struct.ForwardingRuleInsertCall.html) (response) +/// * [insert images](struct.ImageInsertCall.html) (response) +/// * [start instances](struct.InstanceStartCall.html) (response) +/// * [set backup target pools](struct.TargetPoolSetBackupCall.html) (response) +/// * [insert target instances](struct.TargetInstanceInsertCall.html) (response) +/// * [delete forwarding rules](struct.ForwardingRuleDeleteCall.html) (response) +/// * [move instance projects](struct.ProjectMoveInstanceCall.html) (response) +/// * [set target forwarding rules](struct.ForwardingRuleSetTargetCall.html) (response) +/// * [move disk projects](struct.ProjectMoveDiskCall.html) (response) +/// * [insert firewalls](struct.FirewallInsertCall.html) (response) +/// * [remove instance target pools](struct.TargetPoolRemoveInstanceCall.html) (response) +/// * [delete instances](struct.InstanceDeleteCall.html) (response) +/// * [get zone operations](struct.ZoneOperationGetCall.html) (response) +/// * [update http health checks](struct.HttpHealthCheckUpdateCall.html) (response) +/// * [delete routes](struct.RouteDeleteCall.html) (response) +/// * [patch url maps](struct.UrlMapPatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Operation { + /// [Output Only] Status of the operation. Can be one of the following: PENDING, RUNNING, or DONE. + pub status: String, + /// [Output Only] The time that this operation was requested. This is in RFC3339 text format. + #[serde(alias="insertTime")] + pub insert_time: String, + /// [Output Only] If warning messages are generated during processing of the operation, this field will be populated. + pub warnings: Vec, + /// [Output Only] If errors are generated during processing of the operation, this field will be populated. + pub error: OperationError, + /// [Output Only] Unique target ID which identifies a particular incarnation of the target. + #[serde(alias="targetId")] + pub target_id: String, + /// [Output Only] URL of the resource the operation is mutating. + #[serde(alias="targetLink")] + pub target_link: String, + /// [Output Only] The time that this operation was started by the server. This is in RFC3339 text format. + #[serde(alias="startTime")] + pub start_time: String, + /// [Output Only] An optional identifier specified by the client when the mutation was initiated. Must be unique for all operation resources in the project + #[serde(alias="clientOperationId")] + pub client_operation_id: String, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Type of the resource. Always compute#Operation for Operation resources. + pub kind: String, + /// [Output Only] Name of the resource. + pub name: String, + /// [Output Only] URL of the zone where the operation resides. + pub zone: String, + /// [Output Only] URL of the region where the operation resides. Only applicable for regional resources. + pub region: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Type of the operation, such as insert, update, and delete. + #[serde(alias="operationType")] + pub operation_type: String, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as NOT FOUND. + #[serde(alias="httpErrorMessage")] + pub http_error_message: String, + /// [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of operations. This should not be used to guess at when the operation will be complete. This number should be monotonically increasing as the operation progresses. + pub progress: i32, + /// [Output Only] The time that this operation was completed. This is in RFC3339 text format. + #[serde(alias="endTime")] + pub end_time: String, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as 404. + #[serde(alias="httpErrorStatusCode")] + pub http_error_status_code: i32, + /// [Output Only] An optional textual description of the current status of the operation. + #[serde(alias="statusMessage")] + pub status_message: String, + /// [Output Only] User who requested the operation, for example: user@example.com. + pub user: String, +} + +impl ResponseResult for Operation {} + + +/// A Disk resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert disks](struct.DiskInsertCall.html) (request) +/// * [delete disks](struct.DiskDeleteCall.html) (none) +/// * [get disks](struct.DiskGetCall.html) (response) +/// * [create snapshot disks](struct.DiskCreateSnapshotCall.html) (none) +/// * [aggregated list disks](struct.DiskAggregatedListCall.html) (none) +/// * [list disks](struct.DiskListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Disk { + /// [Output Only] The status of disk creation. Applicable statuses includes: CREATING, FAILED, READY, RESTORING. + pub status: Option, + /// The source snapshot used to create this disk. You can provide this as a partial or full URL to the resource. For example, the following are valid values: + /// - https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot + /// - projects/project/global/snapshots/snapshot + /// - global/snapshots/snapshot + #[serde(alias="sourceSnapshot")] + pub source_snapshot: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// The ID value of the image used to create this disk. This value identifies the exact image that was used to create this persistent disk. For example, if you created the persistent disk from an image that was later deleted and recreated under the same name, the source image ID would identify the exact version of the image that was used. + #[serde(alias="sourceImageId")] + pub source_image_id: Option, + /// Any applicable publicly visible licenses. + pub licenses: Option>, + /// The source image used to create this disk. If the source image is deleted from the system, this field will not be set, even if an image with the same name has been re-created. + /// + /// When creating a disk, you can provide a private (custom) image using the following input, and Compute Engine will use the corresponding image from your project. For example: + /// + /// global/images/my-private-image + /// + /// Or you can provide an image from a publicly-available project. For example, to use a Debian image from the debian-cloud project, make sure to include the project in the URL: + /// + /// projects/debian-cloud/global/images/debian-7-wheezy-vYYYYMMDD + /// + /// where vYYYYMMDD is the image version. The fully-qualified URL will also work in both cases. + #[serde(alias="sourceImage")] + pub source_image: Option, + /// [Output Only] The unique ID of the snapshot used to create this disk. This value identifies the exact snapshot that was used to create this persistent disk. For example, if you created the persistent disk from a snapshot that was later deleted and recreated under the same name, the source snapshot ID would identify the exact version of the snapshot that was used. + #[serde(alias="sourceSnapshotId")] + pub source_snapshot_id: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, + /// [Output Only] Type of the resource. Always compute#disk for disks. + pub kind: Option, + /// Size of the persistent disk, specified in GB. You can specify this field when creating a persistent disk using the sourceImage or sourceSnapshot parameter, or specify it alone to create an empty persistent disk. + /// + /// If you specify this field along with sourceImage or sourceSnapshot, the value of sizeGb must not be less than the size of the sourceImage or the size of the snapshot. + #[serde(alias="sizeGb")] + pub size_gb: Option, + /// [Output Only] URL of the zone where the disk resides. + pub zone: Option, + /// URL of the disk type resource describing which disk type to use to create the disk; provided by the client when the disk is created. + #[serde(alias="type")] + pub type_: Option, + /// Internal use only. + pub options: Option, + /// [Output Only] Server-defined fully-qualified URL for this resource. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Disk {} +impl Resource for Disk {} +impl ResponseResult for Disk {} + + +/// Contains a list of TargetHttpProxy resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list target http proxies](struct.TargetHttpProxyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetHttpProxyList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of TargetHttpProxy resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for TargetHttpProxyList {} + + +/// Deprecation status for a public resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [deprecate images](struct.ImageDeprecateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeprecationStatus { + /// An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to DELETED. + pub deleted: Option, + /// An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to DEPRECATED. + pub deprecated: Option, + /// The deprecation state of this resource. This can be DEPRECATED, OBSOLETE, or DELETED. Operations which create a new resource using a DEPRECATED resource will return successfully, but with a warning indicating the deprecated resource and recommending its replacement. Operations which use OBSOLETE or DELETED resources will be rejected and result in an error. + pub state: Option, + /// An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to OBSOLETE. + pub obsolete: Option, + /// The URL of the suggested replacement for a deprecated resource. The suggested replacement resource must be the same kind of resource as the deprecated resource. + pub replacement: Option, +} + +impl RequestValue for DeprecationStatus {} + + +/// [Output Only] Informational warning which replaces the list of disks when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DisksScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for DisksScopedListWarning {} +impl Part for DisksScopedListWarning {} + + +/// A network resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list networks](struct.NetworkListCall.html) (none) +/// * [delete networks](struct.NetworkDeleteCall.html) (none) +/// * [insert networks](struct.NetworkInsertCall.html) (request) +/// * [get networks](struct.NetworkGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Network { + /// [Output Only] Type of the resource. Always compute#network for networks. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// The range of internal addresses that are legal on this network. This range is a CIDR specification, for example: 192.168.0.0/16. Provided by the client when the network is created. + #[serde(alias="IPv4Range")] + pub i_pv4_range: Option, + /// A gateway address for default routing to other networks. This value is read only and is selected by the Google Compute Engine, typically as the first usable address in the IPv4Range. + #[serde(alias="gatewayIPv4")] + pub gateway_i_pv4: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, +} + +impl RequestValue for Network {} +impl Resource for Network {} +impl ResponseResult for Network {} + + +/// A Zone resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list zones](struct.ZoneListCall.html) (none) +/// * [get zones](struct.ZoneGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Zone { + /// [Output Only] Status of the zone, either UP or DOWN. + pub status: String, + /// [Output Only] Type of the resource. Always kind#zone for zones. + pub kind: String, + /// [Output Only] Textual description of the resource. + pub description: String, + /// [Output Only] Any scheduled maintenance windows for this zone. When the zone is in a maintenance window, all resources which reside in the zone will be unavailable. For more information, see Maintenance Windows + #[serde(alias="maintenanceWindows")] + pub maintenance_windows: Vec, + /// [Output Only] The deprecation status associated with this zone. + pub deprecated: DeprecationStatus, + /// [Output Only] Full URL reference to the region which hosts the zone. + pub region: String, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Name of the resource. + pub name: String, +} + +impl Resource for Zone {} +impl ResponseResult for Zone {} + + +/// A ForwardingRule resource. A ForwardingRule resource specifies which pool of target VMs to forward a packet to if it matches the given [IPAddress, IPProtocol, portRange] tuple. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list forwarding rules](struct.ForwardingRuleAggregatedListCall.html) (none) +/// * [get global forwarding rules](struct.GlobalForwardingRuleGetCall.html) (response) +/// * [insert global forwarding rules](struct.GlobalForwardingRuleInsertCall.html) (request) +/// * [insert forwarding rules](struct.ForwardingRuleInsertCall.html) (request) +/// * [delete forwarding rules](struct.ForwardingRuleDeleteCall.html) (none) +/// * [set target forwarding rules](struct.ForwardingRuleSetTargetCall.html) (none) +/// * [get forwarding rules](struct.ForwardingRuleGetCall.html) (response) +/// * [list forwarding rules](struct.ForwardingRuleListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ForwardingRule { + /// Type of the resource. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// Applicable only when 'IPProtocol' is 'TCP', 'UDP' or 'SCTP', only packets addressed to ports in the specified range will be forwarded to 'target'. If 'portRange' is left empty (default value), all ports are forwarded. Forwarding rules with the same [IPAddress, IPProtocol] pair must have disjoint port ranges. + #[serde(alias="portRange")] + pub port_range: Option, + /// URL of the region where the regional forwarding rule resides (output only). This field is not applicable to global forwarding rules. + pub region: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// The IP protocol to which this rule applies, valid options are 'TCP', 'UDP', 'ESP', 'AH' or 'SCTP'. + #[serde(alias="IPProtocol")] + pub ip_protocol: Option, + /// Value of the reserved IP address that this forwarding rule is serving on behalf of. For global forwarding rules, the address must be a global IP; for regional forwarding rules, the address must live in the same region as the forwarding rule. If left empty (default value), an ephemeral IP from the same scope (global or regional) will be assigned. + #[serde(alias="IPAddress")] + pub ip_address: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// The URL of the target resource to receive the matched traffic. For regional forwarding rules, this target must live in the same region as the forwarding rule. For global forwarding rules, this target must be a global TargetHttpProxy resource. + pub target: Option, +} + +impl RequestValue for ForwardingRule {} +impl Resource for ForwardingRule {} +impl ResponseResult for ForwardingRule {} + + +/// An access configuration attached to an instance's network interface. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [add access config instances](struct.InstanceAddAccessConfigCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccessConfig { + /// [Output Only] Type of the resource. Always compute#accessConfig for access configs. + pub kind: Option, + /// The type of configuration. The default and only option is ONE_TO_ONE_NAT. + #[serde(alias="type")] + pub type_: Option, + /// Name of this access configuration. + pub name: Option, + /// An external IP address associated with this instance. Specify an unused static external IP address available to the project or leave this field undefined to use an IP from a shared ephemeral IP address pool. If you specify a static external IP address, it must live in the same region as the zone of the instance. + #[serde(alias="natIP")] + pub nat_ip: Option, +} + +impl RequestValue for AccessConfig {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set url map target http proxies](struct.TargetHttpProxySetUrlMapCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UrlMapReference { + /// no description provided + #[serde(alias="urlMap")] + pub url_map: Option, +} + +impl RequestValue for UrlMapReference {} + + +/// [Output Only] The array of errors encountered while processing this operation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationErrorErrors { + /// [Output Only] An optional, human-readable error message. + pub message: String, + /// [Output Only] The error type identifier for this error. + pub code: String, + /// [Output Only] Indicates the field in the request which caused the error. This property is optional. + pub location: String, +} + +impl NestedType for OperationErrorErrors {} +impl Part for OperationErrorErrors {} + + +/// An HttpHealthCheck resource. This resource defines a template for how individual VMs should be checked for health, via HTTP. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert http health checks](struct.HttpHealthCheckInsertCall.html) (request) +/// * [update http health checks](struct.HttpHealthCheckUpdateCall.html) (request) +/// * [get http health checks](struct.HttpHealthCheckGetCall.html) (response) +/// * [patch http health checks](struct.HttpHealthCheckPatchCall.html) (request) +/// * [list http health checks](struct.HttpHealthCheckListCall.html) (none) +/// * [delete http health checks](struct.HttpHealthCheckDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HttpHealthCheck { + /// Type of the resource. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// How long (in seconds) to wait before claiming failure. The default value is 5 seconds. It is invalid for timeoutSec to have greater value than checkIntervalSec. + #[serde(alias="timeoutSec")] + pub timeout_sec: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, + /// How often (in seconds) to send a health check. The default value is 5 seconds. + #[serde(alias="checkIntervalSec")] + pub check_interval_sec: Option, + /// A so-far healthy VM will be marked unhealthy after this many consecutive failures. The default value is 2. + #[serde(alias="unhealthyThreshold")] + pub unhealthy_threshold: Option, + /// A so-far unhealthy VM will be marked healthy after this many consecutive successes. The default value is 2. + #[serde(alias="healthyThreshold")] + pub healthy_threshold: Option, + /// The value of the host header in the HTTP health check request. If left empty (default value), the public IP on behalf of which this health check is performed will be used. + pub host: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// The TCP port number for the HTTP health check request. The default value is 80. + pub port: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// The request path of the HTTP health check request. The default value is "/". + #[serde(alias="requestPath")] + pub request_path: Option, +} + +impl RequestValue for HttpHealthCheck {} +impl Resource for HttpHealthCheck {} +impl ResponseResult for HttpHealthCheck {} + + +/// The location in Cloud Storage and naming method of the daily usage report. Contains bucket_name and report_name prefix. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set usage export bucket projects](struct.ProjectSetUsageExportBucketCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UsageExportLocation { + /// The name of an existing bucket in Cloud Storage where the usage report object is stored. The Google Service Account is granted write access to this bucket. This is just the bucket name, with no gs:// or https://storage.googleapis.com/ in front of it. + #[serde(alias="bucketName")] + pub bucket_name: Option, + /// An optional prefix for the name of the usage report object stored in bucketName. If not supplied, defaults to usage. The report is stored as a CSV file named report_name_prefix_gce_YYYYMMDD.csv where YYYYMMDD is the day of the usage according to Pacific Time. If you supply a prefix, it should conform to Cloud Storage object naming conventions. + #[serde(alias="reportNamePrefix")] + pub report_name_prefix: Option, +} + +impl RequestValue for UsageExportLocation {} + + +/// [Output Only] Informational warning which replaces the list of addresses when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AddressesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for AddressesScopedListWarning {} +impl Part for AddressesScopedListWarning {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct HealthCheckReference { + /// no description provided + #[serde(alias="healthCheck")] + pub health_check: String, +} + +impl Part for HealthCheckReference {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get health target pools](struct.TargetPoolGetHealthCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolInstanceHealth { + /// Type of resource. + pub kind: String, + /// no description provided + #[serde(alias="healthStatus")] + pub health_status: Vec, +} + +impl ResponseResult for TargetPoolInstanceHealth {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskTypesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for DiskTypesScopedListWarningData {} +impl Part for DiskTypesScopedListWarningData {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list instances](struct.InstanceAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstanceAggregatedList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A map of scoped instance lists. + pub items: HashMap, + /// [Output Only] Type of resource. Always compute#instanceAggregatedList for aggregated lists of Instance resources. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for InstanceAggregatedList {} + + +/// A Machine Type resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list machine types](struct.MachineTypeListCall.html) (none) +/// * [aggregated list machine types](struct.MachineTypeAggregatedListCall.html) (none) +/// * [get machine types](struct.MachineTypeGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineType { + /// [Output Only] The tumber of CPUs exposed to the instance. + #[serde(alias="guestCpus")] + pub guest_cpus: i32, + /// [Deprecated] This property is deprecated and will never be populated with any relevant values. + #[serde(alias="imageSpaceGb")] + pub image_space_gb: i32, + /// Type of the resource. + pub kind: String, + /// [Output Only] An optional textual description of the resource. + pub description: String, + /// [Output Only] The name of the zone where the machine type resides, such as us-central1-a. + pub zone: String, + /// [Output Only] Maximum total persistent disks size (GB) allowed. + #[serde(alias="maximumPersistentDisksSizeGb")] + pub maximum_persistent_disks_size_gb: String, + /// [Output Only] The deprecation status associated with this machine type. + pub deprecated: DeprecationStatus, + /// [Output Only] Maximum persistent disks allowed. + #[serde(alias="maximumPersistentDisks")] + pub maximum_persistent_disks: i32, + /// [Output Only] The amount of physical memory available to the instance, defined in MB. + #[serde(alias="memoryMb")] + pub memory_mb: i32, + /// [Output Only] List of extended scratch disks assigned to the instance. + #[serde(alias="scratchDisks")] + pub scratch_disks: Vec, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Name of the resource. + pub name: String, +} + +impl Resource for MachineType {} +impl ResponseResult for MachineType {} + + +/// [Output Only] Informational warning which replaces the list of operations when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationsScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for OperationsScopedListWarning {} +impl Part for OperationsScopedListWarning {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get health backend services](struct.BackendServiceGetHealthCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BackendServiceGroupHealth { + /// Type of resource. + pub kind: String, + /// no description provided + #[serde(alias="healthStatus")] + pub health_status: Vec, +} + +impl ResponseResult for BackendServiceGroupHealth {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [move instance projects](struct.ProjectMoveInstanceCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InstanceMoveRequest { + /// The URL of the target instance to move. This can be a full or partial URL. For example, the following are all valid URLs to an instance: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances/instance + /// - projects/project/zones/zone/instances/instance + /// - zones/zone/instances/instance + #[serde(alias="targetInstance")] + pub target_instance: Option, + /// The URL of the destination zone to move the instance to. This can be a full or partial URL. For example, the following are all valid URLs to a zone: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone + /// - projects/project/zones/zone + /// - zones/zone + #[serde(alias="destinationZone")] + pub destination_zone: Option, +} + +impl RequestValue for InstanceMoveRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [move disk projects](struct.ProjectMoveDiskCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DiskMoveRequest { + /// The URL of the target disk to move. This can be a full or partial URL. For example, the following are all valid URLs to a disk: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk + /// - projects/project/zones/zone/disks/disk + /// - zones/zone/disks/disk + #[serde(alias="targetDisk")] + pub target_disk: Option, + /// The URL of the destination zone to move the disk to. This can be a full or partial URL. For example, the following are all valid URLs to a zone: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone + /// - projects/project/zones/zone + /// - zones/zone + #[serde(alias="destinationZone")] + pub destination_zone: Option, +} + +impl RequestValue for DiskMoveRequest {} + + +/// [Input Only] Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. +/// +/// This property is mutually exclusive with the source property; you can only define one or the other, but not both. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AttachedDiskInitializeParams { + /// Specifies the size of the disk in base-2 GB. + #[serde(alias="diskSizeGb")] + pub disk_size_gb: String, + /// Specifies the disk name. If not specified, the default is to use the name of the instance. + #[serde(alias="diskName")] + pub disk_name: String, + /// A source image used to create the disk. You can provide a private (custom) image, and Compute Engine will use the corresponding image from your project. For example: + /// + /// global/images/my-private-image + /// + /// Or you can provide an image from a publicly-available project. For example, to use a Debian image from the debian-cloud project, make sure to include the project in the URL: + /// + /// projects/debian-cloud/global/images/debian-7-wheezy-vYYYYMMDD + /// + /// where vYYYYMMDD is the image version. The fully-qualified URL will also work in both cases. + #[serde(alias="sourceImage")] + pub source_image: String, + /// Specifies the disk type to use to create the instance. If not specified, the default is pd-standard, specified using the full URL. For example: + /// + /// https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/pd-standard + /// + /// Other values include pd-ssd and local-ssd. If you define this field, you can provide either the full or partial URL. For example, the following are valid values: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/diskType + /// - projects/project/zones/zone/diskTypes/diskType + /// - zones/zone/diskTypes/diskType + #[serde(alias="diskType")] + pub disk_type: String, +} + +impl Part for AttachedDiskInitializeParams {} + + +/// [Output Only] Any scheduled maintenance windows for this zone. When the zone is in a maintenance window, all resources which reside in the zone will be unavailable. For more information, see Maintenance Windows +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ZoneMaintenanceWindows { + /// [Output Only] Ending time of the maintenance window, in RFC3339 format. + #[serde(alias="endTime")] + pub end_time: String, + /// [Output Only] Textual description of the maintenance window. + pub description: String, + /// [Output Only] Starting time of the maintenance window, in RFC3339 format. + #[serde(alias="beginTime")] + pub begin_time: String, + /// [Output Only] Name of the maintenance window. + pub name: String, +} + +impl NestedType for ZoneMaintenanceWindows {} +impl Part for ZoneMaintenanceWindows {} + + +/// Contains a list of instance resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list instances](struct.InstanceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstanceList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Instance resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#instanceList for lists of Instance resources. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for InstanceList {} + + +/// A TargetPool resource. This resource defines a pool of VMs, associated HttpHealthCheck resources, and the fallback TargetPool. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get health target pools](struct.TargetPoolGetHealthCall.html) (none) +/// * [add instance target pools](struct.TargetPoolAddInstanceCall.html) (none) +/// * [remove instance target pools](struct.TargetPoolRemoveInstanceCall.html) (none) +/// * [remove health check target pools](struct.TargetPoolRemoveHealthCheckCall.html) (none) +/// * [delete target pools](struct.TargetPoolDeleteCall.html) (none) +/// * [insert target pools](struct.TargetPoolInsertCall.html) (request) +/// * [aggregated list target pools](struct.TargetPoolAggregatedListCall.html) (none) +/// * [list target pools](struct.TargetPoolListCall.html) (none) +/// * [add health check target pools](struct.TargetPoolAddHealthCheckCall.html) (none) +/// * [get target pools](struct.TargetPoolGetCall.html) (response) +/// * [set backup target pools](struct.TargetPoolSetBackupCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetPool { + /// This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool (i.e., not as a backup pool to some other target pool). The value of the field must be in [0, 1]. + /// + /// If set, 'backupPool' must also be set. They together define the fallback behavior of the primary target pool: if the ratio of the healthy VMs in the primary pool is at or below this number, traffic arriving at the load-balanced IP will be directed to the backup pool. + /// + /// In case where 'failoverRatio' is not set or all the VMs in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the "force" mode, where traffic will be spread to the healthy VMs with the best effort, or to all VMs when no VM is healthy. + #[serde(alias="failoverRatio")] + pub failover_ratio: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// URL of the region where the target pool resides (output only). + pub region: Option, + /// Type of the resource. + pub kind: Option, + /// Sesssion affinity option, must be one of the following values: 'NONE': Connections from the same client IP may go to any VM in the pool; 'CLIENT_IP': Connections from the same client IP will go to the same VM in the pool while that VM remains healthy. 'CLIENT_IP_PROTO': Connections from the same client IP with the same IP protocol will go to the same VM in the pool while that VM remains healthy. + #[serde(alias="sessionAffinity")] + pub session_affinity: Option, + /// A list of resource URLs to the member VMs serving this pool. They must live in zones contained in the same region as this pool. + pub instances: Option>, + /// This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool, and its 'failoverRatio' field is properly set to a value between [0, 1]. + /// + /// 'backupPool' and 'failoverRatio' together define the fallback behavior of the primary target pool: if the ratio of the healthy VMs in the primary pool is at or below 'failoverRatio', traffic arriving at the load-balanced IP will be directed to the backup pool. + /// + /// In case where 'failoverRatio' and 'backupPool' are not set, or all the VMs in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the "force" mode, where traffic will be spread to the healthy VMs with the best effort, or to all VMs when no VM is healthy. + #[serde(alias="backupPool")] + pub backup_pool: Option, + /// A list of URLs to the HttpHealthCheck resource. A member VM in this pool is considered healthy if and only if all specified health checks pass. An empty list means all member VMs will be considered healthy at all times. + #[serde(alias="healthChecks")] + pub health_checks: Option>, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for TargetPool {} +impl Resource for TargetPool {} +impl ResponseResult for TargetPool {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolsScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for TargetPoolsScopedListWarningData {} +impl Part for TargetPoolsScopedListWarningData {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstancesScopedList { + /// [Output Only] List of instances contained in this scope. + pub instances: Vec, + /// [Output Only] Informational warning which replaces the list of instances when the list is empty. + pub warning: InstancesScopedListWarning, +} + +impl Part for InstancesScopedList {} + + +/// A reserved address resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert global addresses](struct.GlobalAddresseInsertCall.html) (request) +/// * [insert addresses](struct.AddresseInsertCall.html) (request) +/// * [get addresses](struct.AddresseGetCall.html) (response) +/// * [get global addresses](struct.GlobalAddresseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Address { + /// [Output Only] The status of the address, which can be either IN_USE or RESERVED. An address that is RESERVED is currently reserved and available to use. An IN_USE address is currently being used by another resource and is not available. + pub status: Option, + /// [Output Only] Type of the resource. Always compute#address for addresses. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// [Output Only] URL of the region where the regional address resides. This field is not applicable to global addresses. + pub region: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, + /// The static external IP address represented by this resource. + pub address: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// [Output Only] The URLs of the resources that are using this address. + pub users: Option>, +} + +impl RequestValue for Address {} +impl ResponseResult for Address {} + + +/// [Output Only] If errors are generated during processing of the operation, this field will be populated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationError { + /// [Output Only] The array of errors encountered while processing this operation. + pub errors: Vec, +} + +impl NestedType for OperationError {} +impl Part for OperationError {} + + +/// The list of rules specified by this firewall. Each rule specifies a protocol and port-range tuple that describes a permitted connection. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FirewallAllowed { + /// The IP protocol that is allowed for this rule. The protocol type is required when creating a firewall. This value can either be one of the following well known protocol strings (tcp, udp, icmp, esp, ah, sctp), or the IP protocol number. + #[serde(alias="IPProtocol")] + pub ip_protocol: String, + /// An optional list of ports which are allowed. This field is only applicable for UDP or TCP protocol. Each entry must be either an integer or a range. If not specified, connections through any port are allowed + /// + /// Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. + pub ports: Vec, +} + +impl NestedType for FirewallAllowed {} +impl Part for FirewallAllowed {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [add health check target pools](struct.TargetPoolAddHealthCheckCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TargetPoolsAddHealthCheckRequest { + /// Health check URLs to be added to targetPool. + #[serde(alias="healthChecks")] + pub health_checks: Option>, +} + +impl RequestValue for TargetPoolsAddHealthCheckRequest {} + + +/// Contains a list of Network resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list networks](struct.NetworkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct NetworkList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Network resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#networkList for lists of networks. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource . + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for NetworkList {} + + +/// Contains a list of zone resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list zones](struct.ZoneListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ZoneList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Zone resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ZoneList {} + + +/// [Output Only] An informational warning that appears when the machine types list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for MachineTypesScopedListWarning {} +impl Part for MachineTypesScopedListWarning {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get health target pools](struct.TargetPoolGetHealthCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InstanceReference { + /// no description provided + pub instance: Option, +} + +impl RequestValue for InstanceReference {} + + +/// Contains a list of instance template resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list instance templates](struct.InstanceTemplateListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InstanceTemplateList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of InstanceTemplate resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for InstanceTemplateList {} + + +/// Contains a list of TargetInstance resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list target instances](struct.TargetInstanceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetInstanceList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of TargetInstance resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for TargetInstanceList {} + + +/// Contains a list of HttpHealthCheck resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list http health checks](struct.HttpHealthCheckListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct HttpHealthCheckList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of HttpHealthCheck resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for HttpHealthCheckList {} + + +/// A license resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get licenses](struct.LicenseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct License { + /// If true, the customer will be charged license fee for running software that contains this license on an instance. + #[serde(alias="chargesUseFee")] + pub charges_use_fee: bool, + /// [Output Only] Type of resource. Always compute#license for licenses. + pub kind: String, + /// Name of the resource. The name must be 1-63 characters long, and comply with RCF1035. + pub name: String, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl Resource for License {} +impl ResponseResult for License {} + + +/// An instance-attached disk resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [attach disk instances](struct.InstanceAttachDiskCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AttachedDisk { + /// Specifies a unique device name of your choice that is reflected into the /dev/ tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance. + /// + /// If not specified, the server chooses a default device name to apply to this disk, in the form persistent-disks-x, where x is a number assigned by Google Compute Engine. This field is only applicable for persistent disks. + #[serde(alias="deviceName")] + pub device_name: Option, + /// [Output Only] Type of the resource. Always compute#attachedDisk for attached disks. + pub kind: Option, + /// [Input Only] Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. + /// + /// This property is mutually exclusive with the source property; you can only define one or the other, but not both. + #[serde(alias="initializeParams")] + pub initialize_params: Option, + /// Specifies whether the disk will be auto-deleted when the instance is deleted (but not when the disk is detached from the instance). + #[serde(alias="autoDelete")] + pub auto_delete: Option, + /// Assigns a zero-based index to this disk, where 0 is reserved for the boot disk. For example, if you have many disks attached to an instance, each disk would have a unique index number. If not specified, the server will choose an appropriate value. + pub index: Option, + /// Indicates that this is a boot disk. The virtual machine will use the first partition of the disk for its root filesystem. + pub boot: Option, + /// no description provided + pub interface: Option, + /// The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If not specified, the default is to attach the disk in READ_WRITE mode. + pub mode: Option, + /// [Output Only] Any valid publicly visible licenses. + pub licenses: Option>, + /// Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, the default is PERSISTENT. + #[serde(alias="type")] + pub type_: Option, + /// Specifies a valid partial or full URL to an existing Persistent Disk resource. This field is only applicable for persistent disks. + pub source: Option, +} + +impl RequestValue for AttachedDisk {} + + +/// A quotas entry. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Quota { + /// [Output Only] Current usage of this metric. + pub usage: f64, + /// [Output Only] Name of the quota metric. + pub metric: String, + /// [Output Only] Quota limit for this metric. + pub limit: f64, +} + +impl Part for Quota {} + + +/// The route resource. A Route is a rule that specifies how certain packets should be handled by the virtual network. Routes are associated with VMs by tag and the set of Routes for a particular VM is called its routing table. For each packet leaving a VM, the system searches that VM's routing table for a single best matching Route. Routes match packets by destination IP address, preferring smaller or more specific ranges over larger ones. If there is a tie, the system selects the Route with the smallest priority value. If there is still a tie, it uses the layer three and four packet headers to select just one of the remaining matching Routes. The packet is then forwarded as specified by the next_hop field of the winning Route -- either to another VM destination, a VM gateway or a GCE operated gateway. Packets that do not match any Route in the sending VM's routing table will be dropped. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list routes](struct.RouteListCall.html) (none) +/// * [insert routes](struct.RouteInsertCall.html) (request) +/// * [delete routes](struct.RouteDeleteCall.html) (none) +/// * [get routes](struct.RouteGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Route { + /// The URL to a gateway that should handle matching packets. + #[serde(alias="nextHopGateway")] + pub next_hop_gateway: Option, + /// The URL of the local network if it should handle matching packets. + #[serde(alias="nextHopNetwork")] + pub next_hop_network: Option, + /// Type of the resource. + pub kind: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, + /// A list of instance tags to which this route applies. + pub tags: Option>, + /// The URL to an instance that should handle matching packets. + #[serde(alias="nextHopInstance")] + pub next_hop_instance: Option, + /// If potential misconfigurations are detected for this route, this field will be populated with warning messages. + pub warnings: Option>, + /// Breaks ties between Routes of equal specificity. Routes with smaller values win when tied with routes with larger values. + pub priority: Option, + /// The network IP address of an instance that should handle matching packets. + #[serde(alias="nextHopIp")] + pub next_hop_ip: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// Which packets does this route apply to? + #[serde(alias="destRange")] + pub dest_range: Option, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// URL of the network to which this route is applied; provided by the client when the route is created. + pub network: Option, +} + +impl RequestValue for Route {} +impl Resource for Route {} +impl ResponseResult for Route {} + + +/// Informational warning which replaces the list of addresses when the list is empty. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetInstancesScopedListWarning { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for TargetInstancesScopedListWarning {} +impl Part for TargetInstancesScopedListWarning {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set target forwarding rules](struct.ForwardingRuleSetTargetCall.html) (request) +/// * [set backup target pools](struct.TargetPoolSetBackupCall.html) (request) +/// * [set target global forwarding rules](struct.GlobalForwardingRuleSetTargetCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TargetReference { + /// no description provided + pub target: Option, +} + +impl RequestValue for TargetReference {} + + +/// A network interface resource attached to an instance. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct NetworkInterface { + /// An array of configurations for this interface. Currently, , + /// [Output Only] An optional IPV4 internal network address assigned to the instance for this network interface. + #[serde(alias="networkIP")] + pub network_ip: String, + /// [Output Only] The name of the network interface, generated by the server. For network devices, these are eth0, eth1, etc. + pub name: String, + /// URL of the network resource for this instance. This is required for creating an instance but optional when creating a firewall rule. If not specified when creating a firewall rule, the default network is used: + /// + /// global/networks/default + /// + /// If you specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: + /// - https://www.googleapis.com/compute/v1/projects/project/global/networks/network + /// - projects/project/global/networks/network + /// - global/networks/default + pub network: String, +} + +impl Part for NetworkInterface {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list forwarding rules](struct.ForwardingRuleAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ForwardingRuleAggregatedList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A map of scoped forwarding rule lists. + pub items: HashMap, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ForwardingRuleAggregatedList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TestFailure { + /// no description provided + pub path: String, + /// no description provided + #[serde(alias="actualService")] + pub actual_service: String, + /// no description provided + pub host: String, + /// no description provided + #[serde(alias="expectedService")] + pub expected_service: String, +} + +impl Part for TestFailure {} + + +/// [Output Only] List of extended scratch disks assigned to the instance. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MachineTypeScratchDisks { + /// Size of the scratch disk, defined in GB. + #[serde(alias="diskGb")] + pub disk_gb: i32, +} + +impl NestedType for MachineTypeScratchDisks {} +impl Part for MachineTypeScratchDisks {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [aggregated list target pools](struct.TargetPoolAggregatedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolAggregatedList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A map of scoped target pool lists. + pub items: HashMap, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for TargetPoolAggregatedList {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetInstancesScopedList { + /// List of target instances contained in this scope. + #[serde(alias="targetInstances")] + pub target_instances: Vec, + /// Informational warning which replaces the list of addresses when the list is empty. + pub warning: TargetInstancesScopedListWarning, +} + +impl Part for TargetInstancesScopedList {} + + +/// A UrlMap resource. This resource defines the mapping from URL to the BackendService resource, based on the "longest-match" of the URL's host and path. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update url maps](struct.UrlMapUpdateCall.html) (request) +/// * [insert url maps](struct.UrlMapInsertCall.html) (request) +/// * [list url maps](struct.UrlMapListCall.html) (none) +/// * [validate url maps](struct.UrlMapValidateCall.html) (none) +/// * [delete url maps](struct.UrlMapDeleteCall.html) (none) +/// * [get url maps](struct.UrlMapGetCall.html) (response) +/// * [patch url maps](struct.UrlMapPatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UrlMap { + /// Type of the resource. + pub kind: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// The URL of the BackendService resource if none of the hostRules match. + #[serde(alias="defaultService")] + pub default_service: Option, + /// The list of expected URL mappings. Request to update this UrlMap will succeed only all of the test cases pass. + pub tests: Option>, + /// The list of HostRules to use against the URL. + #[serde(alias="hostRules")] + pub host_rules: Option>, + /// Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. This field will be ignored when inserting a UrlMap. An up-to-date fingerprint must be provided in order to update the UrlMap. + pub fingerprint: Option, + /// The list of named PathMatchers to use against the URL. + #[serde(alias="pathMatchers")] + pub path_matchers: Option>, + /// Creation timestamp in RFC3339 text format (output only). + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, + /// Server defined URL for the resource (output only). + #[serde(alias="selfLink")] + pub self_link: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. + pub name: Option, +} + +impl RequestValue for UrlMap {} +impl Resource for UrlMap {} +impl ResponseResult for UrlMap {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RouteWarningsData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for RouteWarningsData {} +impl Part for RouteWarningsData {} + + +/// Contains a list of route resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list routes](struct.RouteListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RouteList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of Route resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for RouteList {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [remove instance target pools](struct.TargetPoolRemoveInstanceCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TargetPoolsRemoveInstanceRequest { + /// URLs of the instances to be removed from targetPool. + pub instances: Option>, +} + +impl RequestValue for TargetPoolsRemoveInstanceRequest {} + + +/// Contains a list of TargetPool resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list target pools](struct.TargetPoolListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of TargetPool resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for TargetPoolList {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InstanceProperties { + /// Allows instances created based on this template to send packets with source IP addresses other than their own and receive packets with destination IP addresses other than their own. If these instances will be used as an IP gateway or it will be set as the next-hop in a Route resource, say true. If unsure, leave this set to false. + #[serde(alias="canIpForward")] + pub can_ip_forward: bool, + /// An optional textual description for the instances created based on the instance template resource; provided by the client when the template is created. + pub description: String, + /// A list of tags to be applied to the instances created based on this template used to identify valid sources or targets for network firewalls. Provided by the client on instance creation. The tags can be later modified by the setTags method. Each tag within the list must comply with RFC1035. + pub tags: Tags, + /// Array of disks associated with instance created based on this template. + pub disks: Vec, + /// Scheduling options for the instances created based on this template. + pub scheduling: Scheduling, + /// Name of the machine type resource describing which machine type to use to host the instances created based on this template; provided by the client when the instance template is created. + #[serde(alias="machineType")] + pub machine_type: String, + /// A list of service accounts each with specified scopes, for which access tokens are to be made available to the instances created based on this template, through metadata queries. + #[serde(alias="serviceAccounts")] + pub service_accounts: Vec, + /// Array of configurations for this interface. This specifies how this interface is configured to interact with other network services, such as connecting to the internet. Currently, ONE_TO_ONE_NAT is the only access config supported. If there are no accessConfigs specified, then this instances created based based on this template will have no external internet access. + #[serde(alias="networkInterfaces")] + pub network_interfaces: Vec, + /// Metadata key/value pairs assigned to instances created based on this template. Consists of custom metadata or predefined keys; see Instance documentation for more information. + pub metadata: Metadata, +} + +impl Part for InstanceProperties {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [remove health check target pools](struct.TargetPoolRemoveHealthCheckCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct TargetPoolsRemoveHealthCheckRequest { + /// Health check URLs to be removed from targetPool. + #[serde(alias="healthChecks")] + pub health_checks: Option>, +} + +impl RequestValue for TargetPoolsRemoveHealthCheckRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DisksScopedList { + /// [Output Only] List of disks contained in this scope. + pub disks: Vec, + /// [Output Only] Informational warning which replaces the list of disks when the list is empty. + pub warning: DisksScopedListWarning, +} + +impl Part for DisksScopedList {} + + +/// An Image resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get images](struct.ImageGetCall.html) (response) +/// * [delete images](struct.ImageDeleteCall.html) (none) +/// * [deprecate images](struct.ImageDeprecateCall.html) (none) +/// * [list images](struct.ImageListCall.html) (none) +/// * [insert images](struct.ImageInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Image { + /// [Output Only] The status of the image. An image can be used to create other resources, such as instances, only after the image has been successfully created and the status is set to READY. Possible values are FAILED, PENDING, or READY. + pub status: Option, + /// [Output Only] Type of the resource. Always compute#image for images. + pub kind: Option, + /// Textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// The parameters of the raw disk image. + #[serde(alias="rawDisk")] + pub raw_disk: Option, + /// The deprecation status associated with this image. + pub deprecated: Option, + /// Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + pub name: Option, + /// Size of the image tar.gz archive stored in Google Cloud Storage (in bytes). + #[serde(alias="archiveSizeBytes")] + pub archive_size_bytes: Option, + /// The ID value of the disk used to create this image. This value may be used to determine whether the image was taken from the current or a previous instance of a given disk name. + #[serde(alias="sourceDiskId")] + pub source_disk_id: Option, + /// Size of the image when restored onto a persistent disk (in GB). + #[serde(alias="diskSizeGb")] + pub disk_size_gb: Option, + /// URL of the The source disk used to create this image. This can be a full or valid partial URL. You must provide either this property or the rawDisk.source property but not both to create an image. For example, the following are valid values: + /// - https://www.googleapis.com/compute/v1/projects/project/zones/zone/disk/disk + /// - projects/project/zones/zone/disk/disk + /// - zones/zone/disks/disk + #[serde(alias="sourceDisk")] + pub source_disk: Option, + /// Any applicable publicly visible licenses. + pub licenses: Option>, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: Option, + /// The type of the image used to create this disk. The default and only value is RAW + #[serde(alias="sourceType")] + pub source_type: Option, +} + +impl RequestValue for Image {} +impl Resource for Image {} +impl ResponseResult for Image {} + + +/// A list of Disk resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list disks](struct.DiskListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DiskList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of persistent disks. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#diskList for lists of disks. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for DiskList {} + + +/// The parameters of the raw disk image. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ImageRawDisk { + /// The format used to encode and transmit the block device, which should be TAR. This is just a container and transmission format and not a runtime format. Provided by the client when the disk image is created. + #[serde(alias="containerType")] + pub container_type: String, + /// The full Google Cloud Storage URL where the disk image is stored. You must provide either this property or the sourceDisk property but not both. + pub source: String, + /// An optional SHA1 checksum of the disk image before unpackaging; provided by the client when the disk image is created. + #[serde(alias="sha1Checksum")] + pub sha1_checksum: String, +} + +impl NestedType for ImageRawDisk {} +impl Part for ImageRawDisk {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationsScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for OperationsScopedListWarningData {} +impl Part for OperationsScopedListWarningData {} + + +/// Contains a list of BackendService resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list backend services](struct.BackendServiceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BackendServiceList { + /// A token used to continue a truncated list request (output only). + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A list of BackendService resources. + pub items: Vec, + /// Type of resource. + pub kind: String, + /// Unique identifier for the resource; defined by the server (output only). + pub id: String, + /// Server defined URL for this resource (output only). + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for BackendServiceList {} + + +/// [Output Only] Metadata for this warning in key: value format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AddressesScopedListWarningData { + /// [Output Only] A key for the warning data. + pub key: String, + /// [Output Only] A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for AddressesScopedListWarningData {} +impl Part for AddressesScopedListWarningData {} + + +/// If potential misconfigurations are detected for this route, this field will be populated with warning messages. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RouteWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: String, + /// [Output Only] The warning type identifier for this warning. + pub code: String, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Vec, +} + +impl NestedType for RouteWarnings {} +impl Part for RouteWarnings {} + + +/// Sets the scheduling options for an Instance. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set scheduling instances](struct.InstanceSetSchedulingCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Scheduling { + /// Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). + #[serde(alias="automaticRestart")] + pub automatic_restart: Option, + /// Defines the maintenance behavior for this instance. The default behavior is MIGRATE. For more information, see Setting maintenance behavior. + #[serde(alias="onHostMaintenance")] + pub on_host_maintenance: Option, +} + +impl RequestValue for Scheduling {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TargetPoolsScopedList { + /// Informational warning which replaces the list of addresses when the list is empty. + pub warning: TargetPoolsScopedListWarning, + /// List of target pools contained in this scope. + #[serde(alias="targetPools")] + pub target_pools: Vec, +} + +impl Part for TargetPoolsScopedList {} + + +/// Contains a list of region resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list regions](struct.RegionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RegionList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// [Output Only] A list of Region resources. + pub items: Vec, + /// [Output Only] Type of resource. Always compute#regionList for lists of regions. + pub kind: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Server defined URL for this resource. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for RegionList {} + + +/// Message containing information of one individual backend. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Backend { + /// The multiplier (a value between 0 and 1e6) of the max capacity (CPU or RPS, depending on 'balancingMode') the group should serve up to. 0 means the group is totally drained. Default value is 1. Valid range is [0, 1e6]. + #[serde(alias="capacityScaler")] + pub capacity_scaler: f32, + /// The max RPS of the group. Can be used with either balancing mode, but required if RATE mode. For RATE mode, either maxRate or maxRatePerInstance must be set. + #[serde(alias="maxRate")] + pub max_rate: i32, + /// URL of a zonal Cloud Resource View resource. This resource view defines the list of instances that serve traffic. Member virtual machine instances from each resource view must live in the same zone as the resource view itself. No two backends in a backend service are allowed to use same Resource View resource. + pub group: String, + /// An optional textual description of the resource, which is provided by the client when the resource is created. + pub description: String, + /// Used when 'balancingMode' is UTILIZATION. This ratio defines the CPU utilization target for the group. The default is 0.8. Valid range is [0, 1]. + #[serde(alias="maxUtilization")] + pub max_utilization: f32, + /// The max RPS that a single backed instance can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerInstance must be set. + #[serde(alias="maxRatePerInstance")] + pub max_rate_per_instance: f32, + /// The balancing mode of this backend, default is UTILIZATION. + #[serde(alias="balancingMode")] + pub balancing_mode: String, +} + +impl Part for Backend {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *disk* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `create_snapshot(...)`, `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.disks(); +/// # } +/// ``` +pub struct DiskMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DiskMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified persistent disk. + pub fn delete(&self, project: &str, zone: &str, disk: &str) -> DiskDeleteCall<'a, C, NC, A> { + DiskDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _disk: disk.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of disks grouped by scope. + pub fn aggregated_list(&self, project: &str) -> DiskAggregatedListCall<'a, C, NC, A> { + DiskAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of persistent disks contained within the specified zone. + pub fn list(&self, project: &str, zone: &str) -> DiskListCall<'a, C, NC, A> { + DiskListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a persistent disk in the specified project using the data included in the request. + pub fn insert(&self, request: &Disk, project: &str, zone: &str) -> DiskInsertCall<'a, C, NC, A> { + DiskInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _source_image: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a snapshot of this disk. + pub fn create_snapshot(&self, request: &Snapshot, project: &str, zone: &str, disk: &str) -> DiskCreateSnapshotCall<'a, C, NC, A> { + DiskCreateSnapshotCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _disk: disk.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a specified persistent disk. + pub fn get(&self, project: &str, zone: &str, disk: &str) -> DiskGetCall<'a, C, NC, A> { + DiskGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _disk: disk.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *addresse* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.addresses(); +/// # } +/// ``` +pub struct AddresseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AddresseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of address resources contained within the specified region. + pub fn list(&self, project: &str, region: &str) -> AddresseListCall<'a, C, NC, A> { + AddresseListCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of addresses grouped by scope. + pub fn aggregated_list(&self, project: &str) -> AddresseAggregatedListCall<'a, C, NC, A> { + AddresseAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified address resource. + pub fn get(&self, project: &str, region: &str, address: &str) -> AddresseGetCall<'a, C, NC, A> { + AddresseGetCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _address: address.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an address resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Address, project: &str, region: &str) -> AddresseInsertCall<'a, C, NC, A> { + AddresseInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified address resource. + pub fn delete(&self, project: &str, region: &str, address: &str) -> AddresseDeleteCall<'a, C, NC, A> { + AddresseDeleteCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _address: address.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *urlMap* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `update(...)` and `validate(...)` +/// // to build up your call. +/// let rb = hub.url_maps(); +/// # } +/// ``` +pub struct UrlMapMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UrlMapMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates a UrlMap resource in the specified project using the data included in the request. + pub fn insert(&self, request: &UrlMap, project: &str) -> UrlMapInsertCall<'a, C, NC, A> { + UrlMapInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified UrlMap resource. + pub fn get(&self, project: &str, url_map: &str) -> UrlMapGetCall<'a, C, NC, A> { + UrlMapGetCall { + hub: self.hub, + _project: project.to_string(), + _url_map: url_map.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Run static validation for the UrlMap. In particular, the tests of the provided UrlMap will be run. Calling this method does NOT create the UrlMap. + pub fn validate(&self, request: &UrlMapsValidateRequest, project: &str, url_map: &str) -> UrlMapValidateCall<'a, C, NC, A> { + UrlMapValidateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _url_map: url_map.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of UrlMap resources available to the specified project. + pub fn list(&self, project: &str) -> UrlMapListCall<'a, C, NC, A> { + UrlMapListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the UrlMap resource. This method supports patch semantics. + pub fn patch(&self, request: &UrlMap, project: &str, url_map: &str) -> UrlMapPatchCall<'a, C, NC, A> { + UrlMapPatchCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _url_map: url_map.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the UrlMap resource. + pub fn update(&self, request: &UrlMap, project: &str, url_map: &str) -> UrlMapUpdateCall<'a, C, NC, A> { + UrlMapUpdateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _url_map: url_map.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified UrlMap resource. + pub fn delete(&self, project: &str, url_map: &str) -> UrlMapDeleteCall<'a, C, NC, A> { + UrlMapDeleteCall { + hub: self.hub, + _project: project.to_string(), + _url_map: url_map.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *globalAddresse* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.global_addresses(); +/// # } +/// ``` +pub struct GlobalAddresseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GlobalAddresseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalAddresseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates an address resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Address, project: &str) -> GlobalAddresseInsertCall<'a, C, NC, A> { + GlobalAddresseInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of global address resources. + pub fn list(&self, project: &str) -> GlobalAddresseListCall<'a, C, NC, A> { + GlobalAddresseListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified address resource. + pub fn get(&self, project: &str, address: &str) -> GlobalAddresseGetCall<'a, C, NC, A> { + GlobalAddresseGetCall { + hub: self.hub, + _project: project.to_string(), + _address: address.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified address resource. + pub fn delete(&self, project: &str, address: &str) -> GlobalAddresseDeleteCall<'a, C, NC, A> { + GlobalAddresseDeleteCall { + hub: self.hub, + _project: project.to_string(), + _address: address.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *snapshot* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.snapshots(); +/// # } +/// ``` +pub struct SnapshotMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SnapshotMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SnapshotMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified persistent disk snapshot resource. + pub fn get(&self, project: &str, snapshot: &str) -> SnapshotGetCall<'a, C, NC, A> { + SnapshotGetCall { + hub: self.hub, + _project: project.to_string(), + _snapshot: snapshot.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of persistent disk snapshot resources contained within the specified project. + pub fn list(&self, project: &str) -> SnapshotListCall<'a, C, NC, A> { + SnapshotListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified persistent disk snapshot resource. + pub fn delete(&self, project: &str, snapshot: &str) -> SnapshotDeleteCall<'a, C, NC, A> { + SnapshotDeleteCall { + hub: self.hub, + _project: project.to_string(), + _snapshot: snapshot.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *diskType* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.disk_types(); +/// # } +/// ``` +pub struct DiskTypeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DiskTypeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskTypeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified disk type resource. + pub fn get(&self, project: &str, zone: &str, disk_type: &str) -> DiskTypeGetCall<'a, C, NC, A> { + DiskTypeGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _disk_type: disk_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of disk type resources grouped by scope. + pub fn aggregated_list(&self, project: &str) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + DiskTypeAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of disk type resources available to the specified project. + pub fn list(&self, project: &str, zone: &str) -> DiskTypeListCall<'a, C, NC, A> { + DiskTypeListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *zone* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.zones(); +/// # } +/// ``` +pub struct ZoneMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ZoneMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified zone resource. + pub fn get(&self, project: &str, zone: &str) -> ZoneGetCall<'a, C, NC, A> { + ZoneGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of zone resources available to the specified project. + pub fn list(&self, project: &str) -> ZoneListCall<'a, C, NC, A> { + ZoneListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *instance* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `add_access_config(...)`, `aggregated_list(...)`, `attach_disk(...)`, `delete(...)`, `delete_access_config(...)`, `detach_disk(...)`, `get(...)`, `get_serial_port_output(...)`, `insert(...)`, `list(...)`, `reset(...)`, `set_disk_auto_delete(...)`, `set_metadata(...)`, `set_scheduling(...)`, `set_tags(...)`, `start(...)` and `stop(...)` +/// // to build up your call. +/// let rb = hub.instances(); +/// # } +/// ``` +pub struct InstanceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for InstanceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Sets an instance's scheduling options. + pub fn set_scheduling(&self, request: &Scheduling, project: &str, zone: &str, instance: &str) -> InstanceSetSchedulingCall<'a, C, NC, A> { + InstanceSetSchedulingCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified Instance resource. For more information, see Shutting down an instance. + pub fn delete(&self, project: &str, zone: &str, instance: &str) -> InstanceDeleteCall<'a, C, NC, A> { + InstanceDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified instance's serial port output. + pub fn get_serial_port_output(&self, project: &str, zone: &str, instance: &str) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> { + InstanceGetSerialPortOutputCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the auto-delete flag for a disk attached to an instance. + pub fn set_disk_auto_delete(&self, project: &str, zone: &str, instance: &str, auto_delete: bool, device_name: &str) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + InstanceSetDiskAutoDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _auto_delete: auto_delete, + _device_name: device_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds an access config to an instance's network interface. + pub fn add_access_config(&self, request: &AccessConfig, project: &str, zone: &str, instance: &str, network_interface: &str) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + InstanceAddAccessConfigCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _network_interface: network_interface.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// This method starts an instance that was stopped using the using the instances().stop method. For more information, see Restart an instance. + pub fn start(&self, project: &str, zone: &str, instance: &str) -> InstanceStartCall<'a, C, NC, A> { + InstanceStartCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified instance resource. + pub fn get(&self, project: &str, zone: &str, instance: &str) -> InstanceGetCall<'a, C, NC, A> { + InstanceGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets tags for the specified instance to the data included in the request. + pub fn set_tags(&self, request: &Tags, project: &str, zone: &str, instance: &str) -> InstanceSetTagCall<'a, C, NC, A> { + InstanceSetTagCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets metadata for the specified instance to the data included in the request. + pub fn set_metadata(&self, request: &Metadata, project: &str, zone: &str, instance: &str) -> InstanceSetMetadataCall<'a, C, NC, A> { + InstanceSetMetadataCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Detaches a disk from an instance. + pub fn detach_disk(&self, project: &str, zone: &str, instance: &str, device_name: &str) -> InstanceDetachDiskCall<'a, C, NC, A> { + InstanceDetachDiskCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _device_name: device_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// This method stops a running instance, shutting it down cleanly, and allows you to restart the instance at a later time. Stopped instances do not incur per-minute, virtual machine usage charges while they are stopped, but any resources that the virtual machine is using, such as persistent disks and static IP addresses,will continue to be charged until they are deleted. For more information, see Stopping an instance. + pub fn stop(&self, project: &str, zone: &str, instance: &str) -> InstanceStopCall<'a, C, NC, A> { + InstanceStopCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an instance resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Instance, project: &str, zone: &str) -> InstanceInsertCall<'a, C, NC, A> { + InstanceInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Performs a hard reset on the instance. + pub fn reset(&self, project: &str, zone: &str, instance: &str) -> InstanceResetCall<'a, C, NC, A> { + InstanceResetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an access config from an instance's network interface. + pub fn delete_access_config(&self, project: &str, zone: &str, instance: &str, access_config: &str, network_interface: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + InstanceDeleteAccessConfigCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _access_config: access_config.to_string(), + _network_interface: network_interface.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Attaches a Disk resource to an instance. + pub fn attach_disk(&self, request: &AttachedDisk, project: &str, zone: &str, instance: &str) -> InstanceAttachDiskCall<'a, C, NC, A> { + InstanceAttachDiskCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of instance resources contained within the specified zone. + pub fn list(&self, project: &str, zone: &str) -> InstanceListCall<'a, C, NC, A> { + InstanceListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn aggregated_list(&self, project: &str) -> InstanceAggregatedListCall<'a, C, NC, A> { + InstanceAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *backendService* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `get_health(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.backend_services(); +/// # } +/// ``` +pub struct BackendServiceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BackendServiceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the most recent health check results for this BackendService. + pub fn get_health(&self, request: &ResourceGroupReference, project: &str, backend_service: &str) -> BackendServiceGetHealthCall<'a, C, NC, A> { + BackendServiceGetHealthCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _backend_service: backend_service.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified BackendService resource. + pub fn delete(&self, project: &str, backend_service: &str) -> BackendServiceDeleteCall<'a, C, NC, A> { + BackendServiceDeleteCall { + hub: self.hub, + _project: project.to_string(), + _backend_service: backend_service.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified BackendService resource. + pub fn get(&self, project: &str, backend_service: &str) -> BackendServiceGetCall<'a, C, NC, A> { + BackendServiceGetCall { + hub: self.hub, + _project: project.to_string(), + _backend_service: backend_service.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the BackendService resource. + pub fn update(&self, request: &BackendService, project: &str, backend_service: &str) -> BackendServiceUpdateCall<'a, C, NC, A> { + BackendServiceUpdateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _backend_service: backend_service.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of BackendService resources available to the specified project. + pub fn list(&self, project: &str) -> BackendServiceListCall<'a, C, NC, A> { + BackendServiceListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the entire content of the BackendService resource. This method supports patch semantics. + pub fn patch(&self, request: &BackendService, project: &str, backend_service: &str) -> BackendServicePatchCall<'a, C, NC, A> { + BackendServicePatchCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _backend_service: backend_service.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a BackendService resource in the specified project using the data included in the request. + pub fn insert(&self, request: &BackendService, project: &str) -> BackendServiceInsertCall<'a, C, NC, A> { + BackendServiceInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *license* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.licenses(); +/// # } +/// ``` +pub struct LicenseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for LicenseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> LicenseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified license resource. + pub fn get(&self, project: &str, license: &str) -> LicenseGetCall<'a, C, NC, A> { + LicenseGetCall { + hub: self.hub, + _project: project.to_string(), + _license: license.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *network* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.networks(); +/// # } +/// ``` +pub struct NetworkMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for NetworkMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> NetworkMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates a network resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Network, project: &str) -> NetworkInsertCall<'a, C, NC, A> { + NetworkInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of network resources available to the specified project. + pub fn list(&self, project: &str) -> NetworkListCall<'a, C, NC, A> { + NetworkListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified network resource. + pub fn delete(&self, project: &str, network: &str) -> NetworkDeleteCall<'a, C, NC, A> { + NetworkDeleteCall { + hub: self.hub, + _project: project.to_string(), + _network: network.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified network resource. + pub fn get(&self, project: &str, network: &str) -> NetworkGetCall<'a, C, NC, A> { + NetworkGetCall { + hub: self.hub, + _project: project.to_string(), + _network: network.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *globalOperation* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.global_operations(); +/// # } +/// ``` +pub struct GlobalOperationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GlobalOperationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalOperationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of operation resources contained within the specified project. + pub fn list(&self, project: &str) -> GlobalOperationListCall<'a, C, NC, A> { + GlobalOperationListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the specified operation resource. + pub fn get(&self, project: &str, operation: &str) -> GlobalOperationGetCall<'a, C, NC, A> { + GlobalOperationGetCall { + hub: self.hub, + _project: project.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified operation resource. + pub fn delete(&self, project: &str, operation: &str) -> GlobalOperationDeleteCall<'a, C, NC, A> { + GlobalOperationDeleteCall { + hub: self.hub, + _project: project.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of all operations grouped by scope. + pub fn aggregated_list(&self, project: &str) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + GlobalOperationAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *region* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.regions(); +/// # } +/// ``` +pub struct RegionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RegionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of region resources available to the specified project. + pub fn list(&self, project: &str) -> RegionListCall<'a, C, NC, A> { + RegionListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified region resource. + pub fn get(&self, project: &str, region: &str) -> RegionGetCall<'a, C, NC, A> { + RegionGetCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *forwardingRule* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `set_target(...)` +/// // to build up your call. +/// let rb = hub.forwarding_rules(); +/// # } +/// ``` +pub struct ForwardingRuleMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ForwardingRuleMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of forwarding rules grouped by scope. + pub fn aggregated_list(&self, project: &str) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + ForwardingRuleAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a ForwardingRule resource in the specified project and region using the data included in the request. + pub fn insert(&self, request: &ForwardingRule, project: &str, region: &str) -> ForwardingRuleInsertCall<'a, C, NC, A> { + ForwardingRuleInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Changes target url for forwarding rule. + pub fn set_target(&self, request: &TargetReference, project: &str, region: &str, forwarding_rule: &str) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + ForwardingRuleSetTargetCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified ForwardingRule resource. + pub fn get(&self, project: &str, region: &str, forwarding_rule: &str) -> ForwardingRuleGetCall<'a, C, NC, A> { + ForwardingRuleGetCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of ForwardingRule resources available to the specified project and region. + pub fn list(&self, project: &str, region: &str) -> ForwardingRuleListCall<'a, C, NC, A> { + ForwardingRuleListCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified ForwardingRule resource. + pub fn delete(&self, project: &str, region: &str, forwarding_rule: &str) -> ForwardingRuleDeleteCall<'a, C, NC, A> { + ForwardingRuleDeleteCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *targetPool* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `add_health_check(...)`, `add_instance(...)`, `aggregated_list(...)`, `delete(...)`, `get(...)`, `get_health(...)`, `insert(...)`, `list(...)`, `remove_health_check(...)`, `remove_instance(...)` and `set_backup(...)` +/// // to build up your call. +/// let rb = hub.target_pools(); +/// # } +/// ``` +pub struct TargetPoolMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TargetPoolMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of TargetPool resources available to the specified project and region. + pub fn list(&self, project: &str, region: &str) -> TargetPoolListCall<'a, C, NC, A> { + TargetPoolListCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds health check URL to targetPool. + pub fn add_health_check(&self, request: &TargetPoolsAddHealthCheckRequest, project: &str, region: &str, target_pool: &str) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + TargetPoolAddHealthCheckCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a TargetPool resource in the specified project and region using the data included in the request. + pub fn insert(&self, request: &TargetPool, project: &str, region: &str) -> TargetPoolInsertCall<'a, C, NC, A> { + TargetPoolInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes health check URL from targetPool. + pub fn remove_health_check(&self, request: &TargetPoolsRemoveHealthCheckRequest, project: &str, region: &str, target_pool: &str) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + TargetPoolRemoveHealthCheckCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the most recent health check results for each IP for the given instance that is referenced by given TargetPool. + pub fn get_health(&self, request: &InstanceReference, project: &str, region: &str, target_pool: &str) -> TargetPoolGetHealthCall<'a, C, NC, A> { + TargetPoolGetHealthCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Changes backup pool configurations. + pub fn set_backup(&self, request: &TargetReference, project: &str, region: &str, target_pool: &str) -> TargetPoolSetBackupCall<'a, C, NC, A> { + TargetPoolSetBackupCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _failover_ratio: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of target pools grouped by scope. + pub fn aggregated_list(&self, project: &str) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + TargetPoolAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified TargetPool resource. + pub fn get(&self, project: &str, region: &str, target_pool: &str) -> TargetPoolGetCall<'a, C, NC, A> { + TargetPoolGetCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds instance url to targetPool. + pub fn add_instance(&self, request: &TargetPoolsAddInstanceRequest, project: &str, region: &str, target_pool: &str) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + TargetPoolAddInstanceCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes instance URL from targetPool. + pub fn remove_instance(&self, request: &TargetPoolsRemoveInstanceRequest, project: &str, region: &str, target_pool: &str) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + TargetPoolRemoveInstanceCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified TargetPool resource. + pub fn delete(&self, project: &str, region: &str, target_pool: &str) -> TargetPoolDeleteCall<'a, C, NC, A> { + TargetPoolDeleteCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _target_pool: target_pool.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *targetInstance* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.target_instances(); +/// # } +/// ``` +pub struct TargetInstanceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TargetInstanceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of TargetInstance resources available to the specified project and zone. + pub fn list(&self, project: &str, zone: &str) -> TargetInstanceListCall<'a, C, NC, A> { + TargetInstanceListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a TargetInstance resource in the specified project and zone using the data included in the request. + pub fn insert(&self, request: &TargetInstance, project: &str, zone: &str) -> TargetInstanceInsertCall<'a, C, NC, A> { + TargetInstanceInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _zone: zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of target instances grouped by scope. + pub fn aggregated_list(&self, project: &str) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + TargetInstanceAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified TargetInstance resource. + pub fn get(&self, project: &str, zone: &str, target_instance: &str) -> TargetInstanceGetCall<'a, C, NC, A> { + TargetInstanceGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _target_instance: target_instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified TargetInstance resource. + pub fn delete(&self, project: &str, zone: &str, target_instance: &str) -> TargetInstanceDeleteCall<'a, C, NC, A> { + TargetInstanceDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _target_instance: target_instance.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *globalForwardingRule* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `set_target(...)` +/// // to build up your call. +/// let rb = hub.global_forwarding_rules(); +/// # } +/// ``` +pub struct GlobalForwardingRuleMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for GlobalForwardingRuleMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified ForwardingRule resource. + pub fn get(&self, project: &str, forwarding_rule: &str) -> GlobalForwardingRuleGetCall<'a, C, NC, A> { + GlobalForwardingRuleGetCall { + hub: self.hub, + _project: project.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified ForwardingRule resource. + pub fn delete(&self, project: &str, forwarding_rule: &str) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> { + GlobalForwardingRuleDeleteCall { + hub: self.hub, + _project: project.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Changes target url for forwarding rule. + pub fn set_target(&self, request: &TargetReference, project: &str, forwarding_rule: &str) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> { + GlobalForwardingRuleSetTargetCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _forwarding_rule: forwarding_rule.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a ForwardingRule resource in the specified project and region using the data included in the request. + pub fn insert(&self, request: &ForwardingRule, project: &str) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> { + GlobalForwardingRuleInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of ForwardingRule resources available to the specified project. + pub fn list(&self, project: &str) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + GlobalForwardingRuleListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *image* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `deprecate(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.images(); +/// # } +/// ``` +pub struct ImageMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ImageMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of image resources available to the specified project. + pub fn list(&self, project: &str) -> ImageListCall<'a, C, NC, A> { + ImageListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified image resource. + pub fn delete(&self, project: &str, image: &str) -> ImageDeleteCall<'a, C, NC, A> { + ImageDeleteCall { + hub: self.hub, + _project: project.to_string(), + _image: image.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the deprecation status of an image. + /// + /// If an empty request body is given, clears the deprecation status instead. + pub fn deprecate(&self, request: &DeprecationStatus, project: &str, image: &str) -> ImageDeprecateCall<'a, C, NC, A> { + ImageDeprecateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _image: image.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an image resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Image, project: &str) -> ImageInsertCall<'a, C, NC, A> { + ImageInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified image resource. + pub fn get(&self, project: &str, image: &str) -> ImageGetCall<'a, C, NC, A> { + ImageGetCall { + hub: self.hub, + _project: project.to_string(), + _image: image.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *machineType* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aggregated_list(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.machine_types(); +/// # } +/// ``` +pub struct MachineTypeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MachineTypeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MachineTypeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of machine type resources grouped by scope. + pub fn aggregated_list(&self, project: &str) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + MachineTypeAggregatedListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified machine type resource. + pub fn get(&self, project: &str, zone: &str, machine_type: &str) -> MachineTypeGetCall<'a, C, NC, A> { + MachineTypeGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _machine_type: machine_type.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of machine type resources available to the specified project. + pub fn list(&self, project: &str, zone: &str) -> MachineTypeListCall<'a, C, NC, A> { + MachineTypeListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *project* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `move_disk(...)`, `move_instance(...)`, `set_common_instance_metadata(...)` and `set_usage_export_bucket(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProjectMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Moves a persistent disk from one zone to another. + pub fn move_disk(&self, request: &DiskMoveRequest, project: &str) -> ProjectMoveDiskCall<'a, C, NC, A> { + ProjectMoveDiskCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets metadata common to all instances within the specified project using the data included in the request. + pub fn set_common_instance_metadata(&self, request: &Metadata, project: &str) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> { + ProjectSetCommonInstanceMetadataCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified project resource. + pub fn get(&self, project: &str) -> ProjectGetCall<'a, C, NC, A> { + ProjectGetCall { + hub: self.hub, + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Moves an instance and its attached persistent disks from one zone to another. + pub fn move_instance(&self, request: &InstanceMoveRequest, project: &str) -> ProjectMoveInstanceCall<'a, C, NC, A> { + ProjectMoveInstanceCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Enables the usage export feature and sets the usage export bucket where reports are stored. If you provide an empty request body using this method, the usage export feature will be disabled. + pub fn set_usage_export_bucket(&self, request: &UsageExportLocation, project: &str) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> { + ProjectSetUsageExportBucketCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *httpHealthCheck* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.http_health_checks(); +/// # } +/// ``` +pub struct HttpHealthCheckMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for HttpHealthCheckMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified HttpHealthCheck resource. + pub fn get(&self, project: &str, http_health_check: &str) -> HttpHealthCheckGetCall<'a, C, NC, A> { + HttpHealthCheckGetCall { + hub: self.hub, + _project: project.to_string(), + _http_health_check: http_health_check.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a HttpHealthCheck resource in the specified project using the data included in the request. This method supports patch semantics. + pub fn patch(&self, request: &HttpHealthCheck, project: &str, http_health_check: &str) -> HttpHealthCheckPatchCall<'a, C, NC, A> { + HttpHealthCheckPatchCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _http_health_check: http_health_check.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of HttpHealthCheck resources available to the specified project. + pub fn list(&self, project: &str) -> HttpHealthCheckListCall<'a, C, NC, A> { + HttpHealthCheckListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified HttpHealthCheck resource. + pub fn delete(&self, project: &str, http_health_check: &str) -> HttpHealthCheckDeleteCall<'a, C, NC, A> { + HttpHealthCheckDeleteCall { + hub: self.hub, + _project: project.to_string(), + _http_health_check: http_health_check.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a HttpHealthCheck resource in the specified project using the data included in the request. + pub fn insert(&self, request: &HttpHealthCheck, project: &str) -> HttpHealthCheckInsertCall<'a, C, NC, A> { + HttpHealthCheckInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a HttpHealthCheck resource in the specified project using the data included in the request. + pub fn update(&self, request: &HttpHealthCheck, project: &str, http_health_check: &str) -> HttpHealthCheckUpdateCall<'a, C, NC, A> { + HttpHealthCheckUpdateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _http_health_check: http_health_check.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *instanceTemplate* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.instance_templates(); +/// # } +/// ``` +pub struct InstanceTemplateMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for InstanceTemplateMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceTemplateMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified instance template resource. + pub fn delete(&self, project: &str, instance_template: &str) -> InstanceTemplateDeleteCall<'a, C, NC, A> { + InstanceTemplateDeleteCall { + hub: self.hub, + _project: project.to_string(), + _instance_template: instance_template.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified instance template resource. + pub fn get(&self, project: &str, instance_template: &str) -> InstanceTemplateGetCall<'a, C, NC, A> { + InstanceTemplateGetCall { + hub: self.hub, + _project: project.to_string(), + _instance_template: instance_template.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of instance template resources contained within the specified project. + pub fn list(&self, project: &str) -> InstanceTemplateListCall<'a, C, NC, A> { + InstanceTemplateListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an instance template resource in the specified project using the data included in the request. + pub fn insert(&self, request: &InstanceTemplate, project: &str) -> InstanceTemplateInsertCall<'a, C, NC, A> { + InstanceTemplateInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *targetHttpProxy* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `set_url_map(...)` +/// // to build up your call. +/// let rb = hub.target_http_proxies(); +/// # } +/// ``` +pub struct TargetHttpProxyMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TargetHttpProxyMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxyMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified TargetHttpProxy resource. + pub fn delete(&self, project: &str, target_http_proxy: &str) -> TargetHttpProxyDeleteCall<'a, C, NC, A> { + TargetHttpProxyDeleteCall { + hub: self.hub, + _project: project.to_string(), + _target_http_proxy: target_http_proxy.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of TargetHttpProxy resources available to the specified project. + pub fn list(&self, project: &str) -> TargetHttpProxyListCall<'a, C, NC, A> { + TargetHttpProxyListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified TargetHttpProxy resource. + pub fn get(&self, project: &str, target_http_proxy: &str) -> TargetHttpProxyGetCall<'a, C, NC, A> { + TargetHttpProxyGetCall { + hub: self.hub, + _project: project.to_string(), + _target_http_proxy: target_http_proxy.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Changes the URL map for TargetHttpProxy. + pub fn set_url_map(&self, request: &UrlMapReference, project: &str, target_http_proxy: &str) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> { + TargetHttpProxySetUrlMapCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _target_http_proxy: target_http_proxy.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a TargetHttpProxy resource in the specified project using the data included in the request. + pub fn insert(&self, request: &TargetHttpProxy, project: &str) -> TargetHttpProxyInsertCall<'a, C, NC, A> { + TargetHttpProxyInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *zoneOperation* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.zone_operations(); +/// # } +/// ``` +pub struct ZoneOperationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ZoneOperationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified zone-specific operation resource. + pub fn delete(&self, project: &str, zone: &str, operation: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + ZoneOperationDeleteCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of operation resources contained within the specified zone. + pub fn list(&self, project: &str, zone: &str) -> ZoneOperationListCall<'a, C, NC, A> { + ZoneOperationListCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the specified zone-specific operation resource. + pub fn get(&self, project: &str, zone: &str, operation: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + ZoneOperationGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *route* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.routes(); +/// # } +/// ``` +pub struct RouteMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RouteMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RouteMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified route resource. + pub fn get(&self, project: &str, route: &str) -> RouteGetCall<'a, C, NC, A> { + RouteGetCall { + hub: self.hub, + _project: project.to_string(), + _route: route.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a route resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Route, project: &str) -> RouteInsertCall<'a, C, NC, A> { + RouteInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of route resources available to the specified project. + pub fn list(&self, project: &str) -> RouteListCall<'a, C, NC, A> { + RouteListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified route resource. + pub fn delete(&self, project: &str, route: &str) -> RouteDeleteCall<'a, C, NC, A> { + RouteDeleteCall { + hub: self.hub, + _project: project.to_string(), + _route: route.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *firewall* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.firewalls(); +/// # } +/// ``` +pub struct FirewallMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FirewallMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates the specified firewall resource with the data included in the request. This method supports patch semantics. + pub fn patch(&self, request: &Firewall, project: &str, firewall: &str) -> FirewallPatchCall<'a, C, NC, A> { + FirewallPatchCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _firewall: firewall.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the specified firewall resource. + pub fn get(&self, project: &str, firewall: &str) -> FirewallGetCall<'a, C, NC, A> { + FirewallGetCall { + hub: self.hub, + _project: project.to_string(), + _firewall: firewall.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a firewall resource in the specified project using the data included in the request. + pub fn insert(&self, request: &Firewall, project: &str) -> FirewallInsertCall<'a, C, NC, A> { + FirewallInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the specified firewall resource with the data included in the request. + pub fn update(&self, request: &Firewall, project: &str, firewall: &str) -> FirewallUpdateCall<'a, C, NC, A> { + FirewallUpdateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _firewall: firewall.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified firewall resource. + pub fn delete(&self, project: &str, firewall: &str) -> FirewallDeleteCall<'a, C, NC, A> { + FirewallDeleteCall { + hub: self.hub, + _project: project.to_string(), + _firewall: firewall.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of firewall resources available to the specified project. + pub fn list(&self, project: &str) -> FirewallListCall<'a, C, NC, A> { + FirewallListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *regionOperation* resources. +/// It is not used directly, but through the `Compute` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-compute1" as compute1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use compute1::Compute; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Compute::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.region_operations(); +/// # } +/// ``` +pub struct RegionOperationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RegionOperationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionOperationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of operation resources contained within the specified region. + pub fn list(&self, project: &str, region: &str) -> RegionOperationListCall<'a, C, NC, A> { + RegionOperationListCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified region-specific operation resource. + pub fn delete(&self, project: &str, region: &str, operation: &str) -> RegionOperationDeleteCall<'a, C, NC, A> { + RegionOperationDeleteCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the specified region-specific operation resource. + pub fn get(&self, project: &str, region: &str, operation: &str) -> RegionOperationGetCall<'a, C, NC, A> { + RegionOperationGetCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Deletes the specified persistent disk. +/// +/// A builder for the *delete* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().delete("project", "zone", "disk") +/// .doit(); +/// # } +/// ``` +pub struct DiskDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _disk: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("disk", self._disk.to_string())); + for &field in ["alt", "project", "zone", "disk"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{disk}", "disk")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "disk"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *disk* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the persistent disk to delete. + pub fn disk(mut self, new_value: &str) -> DiskDeleteCall<'a, C, NC, A> { + self._disk = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of disks grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().aggregated_list("project") +/// .page_token("ea") +/// .max_results(40) +/// .filter("justo") +/// .doit(); +/// # } +/// ``` +pub struct DiskAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DiskAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/disks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> DiskAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> DiskAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> DiskAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of persistent disks contained within the specified zone. +/// +/// A builder for the *list* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().list("project", "zone") +/// .page_token("et") +/// .max_results(60) +/// .filter("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct DiskListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DiskList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> DiskListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> DiskListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> DiskListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a persistent disk in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Disk; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Disk = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().insert(&req, "project", "zone") +/// .source_image("duo") +/// .doit(); +/// # } +/// ``` +pub struct DiskInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Disk, + _project: String, + _zone: String, + _source_image: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._source_image { + params.push(("sourceImage", value.to_string())); + } + for &field in ["alt", "project", "zone", "sourceImage"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Disk) -> DiskInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskInsertCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *source image* query property to the given value. + /// + /// + /// Optional. Source image to restore onto a disk. + pub fn source_image(mut self, new_value: &str) -> DiskInsertCall<'a, C, NC, A> { + self._source_image = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a snapshot of this disk. +/// +/// A builder for the *createSnapshot* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Snapshot; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Snapshot = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().create_snapshot(&req, "project", "zone", "disk") +/// .doit(); +/// # } +/// ``` +pub struct DiskCreateSnapshotCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Snapshot, + _project: String, + _zone: String, + _disk: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskCreateSnapshotCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskCreateSnapshotCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.createSnapshot", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("disk", self._disk.to_string())); + for &field in ["alt", "project", "zone", "disk"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk}/createSnapshot".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{disk}", "disk")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "disk"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Snapshot) -> DiskCreateSnapshotCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskCreateSnapshotCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskCreateSnapshotCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *disk* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the persistent disk to snapshot. + pub fn disk(mut self, new_value: &str) -> DiskCreateSnapshotCall<'a, C, NC, A> { + self._disk = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskCreateSnapshotCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskCreateSnapshotCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskCreateSnapshotCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a specified persistent disk. +/// +/// A builder for the *get* method supported by a *disk* resource. +/// It is not used directly, but through a `DiskMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disks().get("project", "zone", "disk") +/// .doit(); +/// # } +/// ``` +pub struct DiskGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _disk: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Disk)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.disks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("disk", self._disk.to_string())); + for &field in ["alt", "project", "zone", "disk"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{disk}", "disk")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "disk"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *disk* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the persistent disk to return. + pub fn disk(mut self, new_value: &str) -> DiskGetCall<'a, C, NC, A> { + self._disk = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of address resources contained within the specified region. +/// +/// A builder for the *list* method supported by a *addresse* resource. +/// It is not used directly, but through a `AddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.addresses().list("project", "region") +/// .page_token("elitr") +/// .max_results(4) +/// .filter("no") +/// .doit(); +/// # } +/// ``` +pub struct AddresseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AddresseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AddressList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.addresses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "region", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/addresses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> AddresseListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the region for this request. + pub fn region(mut self, new_value: &str) -> AddresseListCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> AddresseListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> AddresseListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> AddresseListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AddresseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AddresseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AddresseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of addresses grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *addresse* resource. +/// It is not used directly, but through a `AddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.addresses().aggregated_list("project") +/// .page_token("eirmod") +/// .max_results(68) +/// .filter("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct AddresseAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AddresseAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AddressAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.addresses.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/addresses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> AddresseAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> AddresseAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> AddresseAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> AddresseAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AddresseAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AddresseAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AddresseAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified address resource. +/// +/// A builder for the *get* method supported by a *addresse* resource. +/// It is not used directly, but through a `AddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.addresses().get("project", "region", "address") +/// .doit(); +/// # } +/// ``` +pub struct AddresseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _address: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AddresseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Address)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.addresses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("address", self._address.to_string())); + for &field in ["alt", "project", "region", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/addresses/{address}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{address}", "address")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "address"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> AddresseGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the region for this request. + pub fn region(mut self, new_value: &str) -> AddresseGetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *address* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the address resource to return. + pub fn address(mut self, new_value: &str) -> AddresseGetCall<'a, C, NC, A> { + self._address = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AddresseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AddresseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AddresseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an address resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *addresse* resource. +/// It is not used directly, but through a `AddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Address; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Address = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.addresses().insert(&req, "project", "region") +/// .doit(); +/// # } +/// ``` +pub struct AddresseInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Address, + _project: String, + _region: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AddresseInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.addresses.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + for &field in ["alt", "project", "region"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/addresses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Address) -> AddresseInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> AddresseInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the region for this request. + pub fn region(mut self, new_value: &str) -> AddresseInsertCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AddresseInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AddresseInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AddresseInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified address resource. +/// +/// A builder for the *delete* method supported by a *addresse* resource. +/// It is not used directly, but through a `AddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.addresses().delete("project", "region", "address") +/// .doit(); +/// # } +/// ``` +pub struct AddresseDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _address: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AddresseDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AddresseDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.addresses.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("address", self._address.to_string())); + for &field in ["alt", "project", "region", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/addresses/{address}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{address}", "address")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "address"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> AddresseDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the region for this request. + pub fn region(mut self, new_value: &str) -> AddresseDeleteCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *address* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the address resource to delete. + pub fn address(mut self, new_value: &str) -> AddresseDeleteCall<'a, C, NC, A> { + self._address = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AddresseDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AddresseDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AddresseDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a UrlMap resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UrlMap; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlMap = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMap, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlMap) -> UrlMapInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified UrlMap resource. +/// +/// A builder for the *get* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().get("project", "urlMap") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _url_map: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlMap)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("urlMap", self._url_map.to_string())); + for &field in ["alt", "project", "urlMap"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{urlMap}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{urlMap}", "urlMap")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "urlMap"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *url map* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the UrlMap resource to return. + pub fn url_map(mut self, new_value: &str) -> UrlMapGetCall<'a, C, NC, A> { + self._url_map = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Run static validation for the UrlMap. In particular, the tests of the provided UrlMap will be run. Calling this method does NOT create the UrlMap. +/// +/// A builder for the *validate* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UrlMapsValidateRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlMapsValidateRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().validate(&req, "project", "urlMap") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapValidateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMapsValidateRequest, + _project: String, + _url_map: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapValidateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapValidateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlMapsValidateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.validate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("urlMap", self._url_map.to_string())); + for &field in ["alt", "project", "urlMap"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{urlMap}/validate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{urlMap}", "urlMap")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "urlMap"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlMapsValidateRequest) -> UrlMapValidateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapValidateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *url map* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the UrlMap resource to be validated as. + pub fn url_map(mut self, new_value: &str) -> UrlMapValidateCall<'a, C, NC, A> { + self._url_map = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapValidateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapValidateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapValidateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of UrlMap resources available to the specified project. +/// +/// A builder for the *list* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().list("project") +/// .page_token("ea") +/// .max_results(21) +/// .filter("dolor") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UrlMapList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> UrlMapListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> UrlMapListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> UrlMapListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the UrlMap resource. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UrlMap; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlMap = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().patch(&req, "project", "urlMap") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMap, + _project: String, + _url_map: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("urlMap", self._url_map.to_string())); + for &field in ["alt", "project", "urlMap"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{urlMap}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{urlMap}", "urlMap")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "urlMap"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlMap) -> UrlMapPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapPatchCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *url map* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the UrlMap resource to update. + pub fn url_map(mut self, new_value: &str) -> UrlMapPatchCall<'a, C, NC, A> { + self._url_map = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the UrlMap resource. +/// +/// A builder for the *update* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UrlMap; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlMap = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().update(&req, "project", "urlMap") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMap, + _project: String, + _url_map: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("urlMap", self._url_map.to_string())); + for &field in ["alt", "project", "urlMap"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{urlMap}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{urlMap}", "urlMap")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "urlMap"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlMap) -> UrlMapUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapUpdateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *url map* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the UrlMap resource to update. + pub fn url_map(mut self, new_value: &str) -> UrlMapUpdateCall<'a, C, NC, A> { + self._url_map = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified UrlMap resource. +/// +/// A builder for the *delete* method supported by a *urlMap* resource. +/// It is not used directly, but through a `UrlMapMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.url_maps().delete("project", "urlMap") +/// .doit(); +/// # } +/// ``` +pub struct UrlMapDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _url_map: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UrlMapDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UrlMapDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.urlMaps.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("urlMap", self._url_map.to_string())); + for &field in ["alt", "project", "urlMap"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/urlMaps/{urlMap}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{urlMap}", "urlMap")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "urlMap"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> UrlMapDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *url map* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the UrlMap resource to delete. + pub fn url_map(mut self, new_value: &str) -> UrlMapDeleteCall<'a, C, NC, A> { + self._url_map = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UrlMapDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UrlMapDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UrlMapDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an address resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *globalAddresse* resource. +/// It is not used directly, but through a `GlobalAddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Address; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Address = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_addresses().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAddresseInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Address, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalAddresseInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalAddresseInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalAddresses.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/addresses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Address) -> GlobalAddresseInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalAddresseInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAddresseInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAddresseInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAddresseInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of global address resources. +/// +/// A builder for the *list* method supported by a *globalAddresse* resource. +/// It is not used directly, but through a `GlobalAddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_addresses().list("project") +/// .page_token("justo") +/// .max_results(49) +/// .filter("vero") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAddresseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalAddresseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalAddresseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AddressList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalAddresses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/addresses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalAddresseListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> GlobalAddresseListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> GlobalAddresseListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> GlobalAddresseListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAddresseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAddresseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAddresseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified address resource. +/// +/// A builder for the *get* method supported by a *globalAddresse* resource. +/// It is not used directly, but through a `GlobalAddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_addresses().get("project", "address") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAddresseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _address: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalAddresseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalAddresseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Address)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalAddresses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("address", self._address.to_string())); + for &field in ["alt", "project", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/addresses/{address}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{address}", "address")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "address"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalAddresseGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *address* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the address resource to return. + pub fn address(mut self, new_value: &str) -> GlobalAddresseGetCall<'a, C, NC, A> { + self._address = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAddresseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAddresseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAddresseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified address resource. +/// +/// A builder for the *delete* method supported by a *globalAddresse* resource. +/// It is not used directly, but through a `GlobalAddresseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_addresses().delete("project", "address") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAddresseDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _address: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalAddresseDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalAddresseDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalAddresses.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("address", self._address.to_string())); + for &field in ["alt", "project", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/addresses/{address}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{address}", "address")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "address"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalAddresseDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *address* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the address resource to delete. + pub fn address(mut self, new_value: &str) -> GlobalAddresseDeleteCall<'a, C, NC, A> { + self._address = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAddresseDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAddresseDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAddresseDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified persistent disk snapshot resource. +/// +/// A builder for the *get* method supported by a *snapshot* resource. +/// It is not used directly, but through a `SnapshotMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.snapshots().get("project", "snapshot") +/// .doit(); +/// # } +/// ``` +pub struct SnapshotGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _snapshot: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SnapshotGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SnapshotGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Snapshot)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.snapshots.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("snapshot", self._snapshot.to_string())); + for &field in ["alt", "project", "snapshot"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/snapshots/{snapshot}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{snapshot}", "snapshot")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "snapshot"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> SnapshotGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *snapshot* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the persistent disk snapshot resource to return. + pub fn snapshot(mut self, new_value: &str) -> SnapshotGetCall<'a, C, NC, A> { + self._snapshot = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SnapshotGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SnapshotGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SnapshotGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of persistent disk snapshot resources contained within the specified project. +/// +/// A builder for the *list* method supported by a *snapshot* resource. +/// It is not used directly, but through a `SnapshotMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.snapshots().list("project") +/// .page_token("consetetur") +/// .max_results(17) +/// .filter("duo") +/// .doit(); +/// # } +/// ``` +pub struct SnapshotListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SnapshotListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SnapshotListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SnapshotList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.snapshots.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/snapshots".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> SnapshotListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> SnapshotListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> SnapshotListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> SnapshotListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SnapshotListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SnapshotListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SnapshotListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified persistent disk snapshot resource. +/// +/// A builder for the *delete* method supported by a *snapshot* resource. +/// It is not used directly, but through a `SnapshotMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.snapshots().delete("project", "snapshot") +/// .doit(); +/// # } +/// ``` +pub struct SnapshotDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _snapshot: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SnapshotDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SnapshotDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.snapshots.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("snapshot", self._snapshot.to_string())); + for &field in ["alt", "project", "snapshot"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/snapshots/{snapshot}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{snapshot}", "snapshot")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "snapshot"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> SnapshotDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *snapshot* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the persistent disk snapshot resource to delete. + pub fn snapshot(mut self, new_value: &str) -> SnapshotDeleteCall<'a, C, NC, A> { + self._snapshot = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SnapshotDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SnapshotDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SnapshotDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified disk type resource. +/// +/// A builder for the *get* method supported by a *diskType* resource. +/// It is not used directly, but through a `DiskTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disk_types().get("project", "zone", "diskType") +/// .doit(); +/// # } +/// ``` +pub struct DiskTypeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _disk_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskTypeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskTypeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DiskType)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.diskTypes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("diskType", self._disk_type.to_string())); + for &field in ["alt", "project", "zone", "diskType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/diskTypes/{diskType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{diskType}", "diskType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "diskType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *disk type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the disk type resource to return. + pub fn disk_type(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, NC, A> { + self._disk_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskTypeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskTypeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of disk type resources grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *diskType* resource. +/// It is not used directly, but through a `DiskTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disk_types().aggregated_list("project") +/// .page_token("nonumy") +/// .max_results(88) +/// .filter("sanctus") +/// .doit(); +/// # } +/// ``` +pub struct DiskTypeAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskTypeAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskTypeAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DiskTypeAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.diskTypes.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/diskTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskTypeAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskTypeAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of disk type resources available to the specified project. +/// +/// A builder for the *list* method supported by a *diskType* resource. +/// It is not used directly, but through a `DiskTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.disk_types().list("project", "zone") +/// .page_token("labore") +/// .max_results(64) +/// .filter("ea") +/// .doit(); +/// # } +/// ``` +pub struct DiskTypeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DiskTypeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DiskTypeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DiskTypeList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.diskTypes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/diskTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> DiskTypeListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> DiskTypeListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> DiskTypeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> DiskTypeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> DiskTypeListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DiskTypeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DiskTypeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified zone resource. +/// +/// A builder for the *get* method supported by a *zone* resource. +/// It is not used directly, but through a `ZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zones().get("project", "zone") +/// .doit(); +/// # } +/// ``` +pub struct ZoneGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Zone)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.zones.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + for &field in ["alt", "project", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ZoneGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone resource to return. + pub fn zone(mut self, new_value: &str) -> ZoneGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of zone resources available to the specified project. +/// +/// A builder for the *list* method supported by a *zone* resource. +/// It is not used directly, but through a `ZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zones().list("project") +/// .page_token("nonumy") +/// .max_results(72) +/// .filter("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct ZoneListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ZoneList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.zones.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> ZoneListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> ZoneListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets an instance's scheduling options. +/// +/// A builder for the *setScheduling* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Scheduling; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Scheduling = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().set_scheduling(&req, "project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceSetSchedulingCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Scheduling, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceSetSchedulingCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceSetSchedulingCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.setScheduling", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/setScheduling".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Scheduling) -> InstanceSetSchedulingCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceSetSchedulingCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceSetSchedulingCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Instance name. + pub fn instance(mut self, new_value: &str) -> InstanceSetSchedulingCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceSetSchedulingCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceSetSchedulingCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceSetSchedulingCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified Instance resource. For more information, see Shutting down an instance. +/// +/// A builder for the *delete* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().delete("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance resource to delete. + pub fn instance(mut self, new_value: &str) -> InstanceDeleteCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified instance's serial port output. +/// +/// A builder for the *getSerialPortOutput* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().get_serial_port_output("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGetSerialPortOutputCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceGetSerialPortOutputCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceGetSerialPortOutputCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SerialPortOutput)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.getSerialPortOutput", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/serialPort".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance scoping this request. + pub fn instance(mut self, new_value: &str) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGetSerialPortOutputCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets the auto-delete flag for a disk attached to an instance. +/// +/// A builder for the *setDiskAutoDelete* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().set_disk_auto_delete("project", "zone", "instance", false, "deviceName") +/// .doit(); +/// # } +/// ``` +pub struct InstanceSetDiskAutoDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _auto_delete: bool, + _device_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceSetDiskAutoDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.setDiskAutoDelete", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + params.push(("autoDelete", self._auto_delete.to_string())); + params.push(("deviceName", self._device_name.to_string())); + for &field in ["alt", "project", "zone", "instance", "autoDelete", "deviceName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/setDiskAutoDelete".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The instance name. + pub fn instance(mut self, new_value: &str) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *auto delete* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Whether to auto-delete the disk when the instance is deleted. + pub fn auto_delete(mut self, new_value: bool) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._auto_delete = new_value; + self + } + /// Sets the *device name* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The device name of the disk to modify. + pub fn device_name(mut self, new_value: &str) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._device_name = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceSetDiskAutoDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds an access config to an instance's network interface. +/// +/// A builder for the *addAccessConfig* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::AccessConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccessConfig = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().add_access_config(&req, "project", "zone", "instance", "networkInterface") +/// .doit(); +/// # } +/// ``` +pub struct InstanceAddAccessConfigCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: AccessConfig, + _project: String, + _zone: String, + _instance: String, + _network_interface: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceAddAccessConfigCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceAddAccessConfigCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.addAccessConfig", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + params.push(("networkInterface", self._network_interface.to_string())); + for &field in ["alt", "project", "zone", "instance", "networkInterface"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/addAccessConfig".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccessConfig) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The instance name for this request. + pub fn instance(mut self, new_value: &str) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *network interface* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the network interface to add to this instance. + pub fn network_interface(mut self, new_value: &str) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._network_interface = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceAddAccessConfigCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceAddAccessConfigCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceAddAccessConfigCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// This method starts an instance that was stopped using the using the instances().stop method. For more information, see Restart an instance. +/// +/// A builder for the *start* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().start("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceStartCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceStartCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceStartCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.start", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/start".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceStartCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceStartCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance resource to start. + pub fn instance(mut self, new_value: &str) -> InstanceStartCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceStartCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceStartCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceStartCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified instance resource. +/// +/// A builder for the *get* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().get("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Instance)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the The name of the zone for this request.. + pub fn zone(mut self, new_value: &str) -> InstanceGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance resource to return. + pub fn instance(mut self, new_value: &str) -> InstanceGetCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets tags for the specified instance to the data included in the request. +/// +/// A builder for the *setTags* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Tags; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Tags = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().set_tags(&req, "project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceSetTagCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Tags, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceSetTagCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceSetTagCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.setTags", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/setTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Tags) -> InstanceSetTagCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceSetTagCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceSetTagCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance scoping this request. + pub fn instance(mut self, new_value: &str) -> InstanceSetTagCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceSetTagCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceSetTagCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceSetTagCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets metadata for the specified instance to the data included in the request. +/// +/// A builder for the *setMetadata* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Metadata; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Metadata = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().set_metadata(&req, "project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceSetMetadataCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Metadata, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceSetMetadataCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceSetMetadataCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.setMetadata", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/setMetadata".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Metadata) -> InstanceSetMetadataCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceSetMetadataCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceSetMetadataCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance scoping this request. + pub fn instance(mut self, new_value: &str) -> InstanceSetMetadataCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceSetMetadataCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceSetMetadataCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceSetMetadataCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Detaches a disk from an instance. +/// +/// A builder for the *detachDisk* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().detach_disk("project", "zone", "instance", "deviceName") +/// .doit(); +/// # } +/// ``` +pub struct InstanceDetachDiskCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _device_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceDetachDiskCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceDetachDiskCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.detachDisk", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + params.push(("deviceName", self._device_name.to_string())); + for &field in ["alt", "project", "zone", "instance", "deviceName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/detachDisk".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceDetachDiskCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceDetachDiskCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Instance name. + pub fn instance(mut self, new_value: &str) -> InstanceDetachDiskCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *device name* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Disk device name to detach. + pub fn device_name(mut self, new_value: &str) -> InstanceDetachDiskCall<'a, C, NC, A> { + self._device_name = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceDetachDiskCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceDetachDiskCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceDetachDiskCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// This method stops a running instance, shutting it down cleanly, and allows you to restart the instance at a later time. Stopped instances do not incur per-minute, virtual machine usage charges while they are stopped, but any resources that the virtual machine is using, such as persistent disks and static IP addresses,will continue to be charged until they are deleted. For more information, see Stopping an instance. +/// +/// A builder for the *stop* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().stop("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceStopCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceStopCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceStopCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.stop", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceStopCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceStopCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance resource to start. + pub fn instance(mut self, new_value: &str) -> InstanceStopCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceStopCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceStopCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceStopCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an instance resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Instance; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Instance = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().insert(&req, "project", "zone") +/// .doit(); +/// # } +/// ``` +pub struct InstanceInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Instance, + _project: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + for &field in ["alt", "project", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Instance) -> InstanceInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceInsertCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Performs a hard reset on the instance. +/// +/// A builder for the *reset* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().reset("project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceResetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceResetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceResetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.reset", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/reset".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceResetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceResetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance scoping this request. + pub fn instance(mut self, new_value: &str) -> InstanceResetCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceResetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceResetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceResetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an access config from an instance's network interface. +/// +/// A builder for the *deleteAccessConfig* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().delete_access_config("project", "zone", "instance", "accessConfig", "networkInterface") +/// .doit(); +/// # } +/// ``` +pub struct InstanceDeleteAccessConfigCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance: String, + _access_config: String, + _network_interface: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceDeleteAccessConfigCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceDeleteAccessConfigCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.deleteAccessConfig", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + params.push(("accessConfig", self._access_config.to_string())); + params.push(("networkInterface", self._network_interface.to_string())); + for &field in ["alt", "project", "zone", "instance", "accessConfig", "networkInterface"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/deleteAccessConfig".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The instance name for this request. + pub fn instance(mut self, new_value: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *access config* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the access config to delete. + pub fn access_config(mut self, new_value: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._access_config = new_value.to_string(); + self + } + /// Sets the *network interface* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the network interface. + pub fn network_interface(mut self, new_value: &str) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._network_interface = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceDeleteAccessConfigCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Attaches a Disk resource to an instance. +/// +/// A builder for the *attachDisk* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::AttachedDisk; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AttachedDisk = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().attach_disk(&req, "project", "zone", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceAttachDiskCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: AttachedDisk, + _project: String, + _zone: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceAttachDiskCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceAttachDiskCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.attachDisk", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("instance", self._instance.to_string())); + for &field in ["alt", "project", "zone", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/attachDisk".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instance}", "instance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "instance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AttachedDisk) -> InstanceAttachDiskCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceAttachDiskCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceAttachDiskCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Instance name. + pub fn instance(mut self, new_value: &str) -> InstanceAttachDiskCall<'a, C, NC, A> { + self._instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceAttachDiskCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceAttachDiskCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceAttachDiskCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of instance resources contained within the specified zone. +/// +/// A builder for the *list* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().list("project", "zone") +/// .page_token("takimata") +/// .max_results(58) +/// .filter("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct InstanceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> InstanceListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> InstanceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> InstanceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> InstanceListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *aggregatedList* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instances().aggregated_list("project") +/// .page_token("Lorem") +/// .max_results(51) +/// .filter("diam") +/// .doit(); +/// # } +/// ``` +pub struct InstanceAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instances.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/instances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> InstanceAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> InstanceAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> InstanceAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> InstanceAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the most recent health check results for this BackendService. +/// +/// A builder for the *getHealth* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::ResourceGroupReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ResourceGroupReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().get_health(&req, "project", "backendService") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceGetHealthCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: ResourceGroupReference, + _project: String, + _backend_service: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceGetHealthCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceGetHealthCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BackendServiceGroupHealth)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.getHealth", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("backendService", self._backend_service.to_string())); + for &field in ["alt", "project", "backendService"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}/getHealth".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{backendService}", "backendService")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "backendService"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ResourceGroupReference) -> BackendServiceGetHealthCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> BackendServiceGetHealthCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *backend service* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the BackendService resource to which the queried instance belongs. + pub fn backend_service(mut self, new_value: &str) -> BackendServiceGetHealthCall<'a, C, NC, A> { + self._backend_service = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceGetHealthCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceGetHealthCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceGetHealthCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified BackendService resource. +/// +/// A builder for the *delete* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().delete("project", "backendService") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _backend_service: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("backendService", self._backend_service.to_string())); + for &field in ["alt", "project", "backendService"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{backendService}", "backendService")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "backendService"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServiceDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *backend service* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the BackendService resource to delete. + pub fn backend_service(mut self, new_value: &str) -> BackendServiceDeleteCall<'a, C, NC, A> { + self._backend_service = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified BackendService resource. +/// +/// A builder for the *get* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().get("project", "backendService") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _backend_service: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BackendService)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("backendService", self._backend_service.to_string())); + for &field in ["alt", "project", "backendService"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{backendService}", "backendService")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "backendService"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServiceGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *backend service* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the BackendService resource to return. + pub fn backend_service(mut self, new_value: &str) -> BackendServiceGetCall<'a, C, NC, A> { + self._backend_service = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the BackendService resource. +/// +/// A builder for the *update* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::BackendService; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: BackendService = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().update(&req, "project", "backendService") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: BackendService, + _project: String, + _backend_service: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("backendService", self._backend_service.to_string())); + for &field in ["alt", "project", "backendService"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{backendService}", "backendService")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "backendService"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &BackendService) -> BackendServiceUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServiceUpdateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *backend service* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the BackendService resource to update. + pub fn backend_service(mut self, new_value: &str) -> BackendServiceUpdateCall<'a, C, NC, A> { + self._backend_service = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of BackendService resources available to the specified project. +/// +/// A builder for the *list* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().list("project") +/// .page_token("sanctus") +/// .max_results(74) +/// .filter("dolor") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BackendServiceList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServiceListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> BackendServiceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> BackendServiceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> BackendServiceListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Update the entire content of the BackendService resource. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::BackendService; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: BackendService = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().patch(&req, "project", "backendService") +/// .doit(); +/// # } +/// ``` +pub struct BackendServicePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: BackendService, + _project: String, + _backend_service: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServicePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServicePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("backendService", self._backend_service.to_string())); + for &field in ["alt", "project", "backendService"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices/{backendService}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{backendService}", "backendService")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "backendService"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &BackendService) -> BackendServicePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServicePatchCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *backend service* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the BackendService resource to update. + pub fn backend_service(mut self, new_value: &str) -> BackendServicePatchCall<'a, C, NC, A> { + self._backend_service = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServicePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServicePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServicePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a BackendService resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *backendService* resource. +/// It is not used directly, but through a `BackendServiceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::BackendService; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: BackendService = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backend_services().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct BackendServiceInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: BackendService, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BackendServiceInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BackendServiceInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.backendServices.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/backendServices".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &BackendService) -> BackendServiceInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> BackendServiceInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackendServiceInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackendServiceInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackendServiceInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified license resource. +/// +/// A builder for the *get* method supported by a *license* resource. +/// It is not used directly, but through a `LicenseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.licenses().get("project", "license") +/// .doit(); +/// # } +/// ``` +pub struct LicenseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _license: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LicenseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LicenseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, License)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.licenses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("license", self._license.to_string())); + for &field in ["alt", "project", "license"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/licenses/{license}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{license}", "license")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "license"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> LicenseGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *license* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the license resource to return. + pub fn license(mut self, new_value: &str) -> LicenseGetCall<'a, C, NC, A> { + self._license = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LicenseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LicenseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LicenseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a network resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *network* resource. +/// It is not used directly, but through a `NetworkMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Network; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Network = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.networks().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct NetworkInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Network, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NetworkInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NetworkInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.networks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/networks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Network) -> NetworkInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> NetworkInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NetworkInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NetworkInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NetworkInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of network resources available to the specified project. +/// +/// A builder for the *list* method supported by a *network* resource. +/// It is not used directly, but through a `NetworkMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.networks().list("project") +/// .page_token("justo") +/// .max_results(67) +/// .filter("vero") +/// .doit(); +/// # } +/// ``` +pub struct NetworkListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NetworkListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NetworkListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, NetworkList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.networks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/networks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> NetworkListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> NetworkListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> NetworkListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> NetworkListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NetworkListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NetworkListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NetworkListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified network resource. +/// +/// A builder for the *delete* method supported by a *network* resource. +/// It is not used directly, but through a `NetworkMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.networks().delete("project", "network") +/// .doit(); +/// # } +/// ``` +pub struct NetworkDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _network: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NetworkDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NetworkDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.networks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("network", self._network.to_string())); + for &field in ["alt", "project", "network"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{network}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{network}", "network")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "network"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> NetworkDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *network* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the network resource to delete. + pub fn network(mut self, new_value: &str) -> NetworkDeleteCall<'a, C, NC, A> { + self._network = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NetworkDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NetworkDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NetworkDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified network resource. +/// +/// A builder for the *get* method supported by a *network* resource. +/// It is not used directly, but through a `NetworkMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.networks().get("project", "network") +/// .doit(); +/// # } +/// ``` +pub struct NetworkGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _network: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for NetworkGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> NetworkGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Network)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.networks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("network", self._network.to_string())); + for &field in ["alt", "project", "network"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{network}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{network}", "network")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "network"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> NetworkGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *network* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the network resource to return. + pub fn network(mut self, new_value: &str) -> NetworkGetCall<'a, C, NC, A> { + self._network = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NetworkGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NetworkGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NetworkGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of operation resources contained within the specified project. +/// +/// A builder for the *list* method supported by a *globalOperation* resource. +/// It is not used directly, but through a `GlobalOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_operations().list("project") +/// .page_token("sed") +/// .max_results(91) +/// .filter("invidunt") +/// .doit(); +/// # } +/// ``` +pub struct GlobalOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalOperations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalOperationListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> GlobalOperationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> GlobalOperationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> GlobalOperationListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the specified operation resource. +/// +/// A builder for the *get* method supported by a *globalOperation* resource. +/// It is not used directly, but through a `GlobalOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_operations().get("project", "operation") +/// .doit(); +/// # } +/// ``` +pub struct GlobalOperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalOperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalOperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalOperations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["alt", "project", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalOperationGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to return. + pub fn operation(mut self, new_value: &str) -> GlobalOperationGetCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalOperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalOperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalOperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified operation resource. +/// +/// A builder for the *delete* method supported by a *globalOperation* resource. +/// It is not used directly, but through a `GlobalOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_operations().delete("project", "operation") +/// .doit(); +/// # } +/// ``` +pub struct GlobalOperationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalOperationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalOperationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalOperations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["project", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalOperationDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to delete. + pub fn operation(mut self, new_value: &str) -> GlobalOperationDeleteCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalOperationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of all operations grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *globalOperation* resource. +/// It is not used directly, but through a `GlobalOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_operations().aggregated_list("project") +/// .page_token("sea") +/// .max_results(58) +/// .filter("At") +/// .doit(); +/// # } +/// ``` +pub struct GlobalOperationAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalOperationAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalOperationAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalOperations.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalOperationAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalOperationAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalOperationAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of region resources available to the specified project. +/// +/// A builder for the *list* method supported by a *region* resource. +/// It is not used directly, but through a `RegionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.regions().list("project") +/// .page_token("consetetur") +/// .max_results(22) +/// .filter("accusam") +/// .doit(); +/// # } +/// ``` +pub struct RegionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RegionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.regions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> RegionListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> RegionListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> RegionListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> RegionListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified region resource. +/// +/// A builder for the *get* method supported by a *region* resource. +/// It is not used directly, but through a `RegionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.regions().get("project", "region") +/// .doit(); +/// # } +/// ``` +pub struct RegionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Region)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.regions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + for &field in ["alt", "project", "region"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> RegionGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region resource to return. + pub fn region(mut self, new_value: &str) -> RegionGetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of forwarding rules grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().aggregated_list("project") +/// .page_token("aliquyam") +/// .max_results(7) +/// .filter("ea") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ForwardingRuleAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/forwardingRules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a ForwardingRule resource in the specified project and region using the data included in the request. +/// +/// A builder for the *insert* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::ForwardingRule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ForwardingRule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().insert(&req, "project", "region") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: ForwardingRule, + _project: String, + _region: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + for &field in ["alt", "project", "region"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/forwardingRules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ForwardingRule) -> ForwardingRuleInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> ForwardingRuleInsertCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Changes target url for forwarding rule. +/// +/// A builder for the *setTarget* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().set_target(&req, "project", "region", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleSetTargetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetReference, + _project: String, + _region: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleSetTargetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleSetTargetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.setTarget", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "region", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/forwardingRules/{forwardingRule}/setTarget".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetReference) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource in which target is to be set. + pub fn forwarding_rule(mut self, new_value: &str) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleSetTargetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleSetTargetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleSetTargetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified ForwardingRule resource. +/// +/// A builder for the *get* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().get("project", "region", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ForwardingRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "region", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/forwardingRules/{forwardingRule}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> ForwardingRuleGetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource to return. + pub fn forwarding_rule(mut self, new_value: &str) -> ForwardingRuleGetCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of ForwardingRule resources available to the specified project and region. +/// +/// A builder for the *list* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().list("project", "region") +/// .page_token("labore") +/// .max_results(40) +/// .filter("et") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ForwardingRuleList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "region", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/forwardingRules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> ForwardingRuleListCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ForwardingRuleListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> ForwardingRuleListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> ForwardingRuleListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified ForwardingRule resource. +/// +/// A builder for the *delete* method supported by a *forwardingRule* resource. +/// It is not used directly, but through a `ForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.forwarding_rules().delete("project", "region", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct ForwardingRuleDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ForwardingRuleDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ForwardingRuleDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.forwardingRules.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "region", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/forwardingRules/{forwardingRule}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> ForwardingRuleDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> ForwardingRuleDeleteCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource to delete. + pub fn forwarding_rule(mut self, new_value: &str) -> ForwardingRuleDeleteCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ForwardingRuleDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ForwardingRuleDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ForwardingRuleDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of TargetPool resources available to the specified project and region. +/// +/// A builder for the *list* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().list("project", "region") +/// .page_token("et") +/// .max_results(37) +/// .filter("eos") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetPoolList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "region", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolListCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> TargetPoolListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> TargetPoolListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> TargetPoolListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds health check URL to targetPool. +/// +/// A builder for the *addHealthCheck* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetPoolsAddHealthCheckRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetPoolsAddHealthCheckRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().add_health_check(&req, "project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolAddHealthCheckCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetPoolsAddHealthCheckRequest, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolAddHealthCheckCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolAddHealthCheckCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.addHealthCheck", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/addHealthCheck".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetPoolsAddHealthCheckRequest) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to which health_check_url is to be added. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolAddHealthCheckCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a TargetPool resource in the specified project and region using the data included in the request. +/// +/// A builder for the *insert* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetPool; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetPool = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().insert(&req, "project", "region") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetPool, + _project: String, + _region: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + for &field in ["alt", "project", "region"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetPool) -> TargetPoolInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolInsertCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes health check URL from targetPool. +/// +/// A builder for the *removeHealthCheck* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetPoolsRemoveHealthCheckRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetPoolsRemoveHealthCheckRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().remove_health_check(&req, "project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolRemoveHealthCheckCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetPoolsRemoveHealthCheckRequest, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolRemoveHealthCheckCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.removeHealthCheck", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/removeHealthCheck".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetPoolsRemoveHealthCheckRequest) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to which health_check_url is to be removed. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolRemoveHealthCheckCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the most recent health check results for each IP for the given instance that is referenced by given TargetPool. +/// +/// A builder for the *getHealth* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::InstanceReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InstanceReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().get_health(&req, "project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolGetHealthCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceReference, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolGetHealthCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolGetHealthCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetPoolInstanceHealth)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.getHealth", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/getHealth".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InstanceReference) -> TargetPoolGetHealthCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> TargetPoolGetHealthCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolGetHealthCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to which the queried instance belongs. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolGetHealthCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolGetHealthCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolGetHealthCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolGetHealthCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Changes backup pool configurations. +/// +/// A builder for the *setBackup* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().set_backup(&req, "project", "region", "targetPool") +/// .failover_ratio(0.189075671793) +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolSetBackupCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetReference, + _project: String, + _region: String, + _target_pool: String, + _failover_ratio: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolSetBackupCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolSetBackupCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.setBackup", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + if let Some(value) = self._failover_ratio { + params.push(("failoverRatio", value.to_string())); + } + for &field in ["alt", "project", "region", "targetPool", "failoverRatio"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/setBackup".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetReference) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource for which the backup is to be set. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *failover ratio* query property to the given value. + /// + /// + /// New failoverRatio value for the containing target pool. + pub fn failover_ratio(mut self, new_value: f32) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._failover_ratio = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolSetBackupCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolSetBackupCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolSetBackupCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of target pools grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().aggregated_list("project") +/// .page_token("invidunt") +/// .max_results(79) +/// .filter("labore") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetPoolAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/targetPools".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified TargetPool resource. +/// +/// A builder for the *get* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().get("project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetPool)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolGetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to return. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolGetCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds instance url to targetPool. +/// +/// A builder for the *addInstance* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetPoolsAddInstanceRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetPoolsAddInstanceRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().add_instance(&req, "project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolAddInstanceCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetPoolsAddInstanceRequest, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolAddInstanceCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolAddInstanceCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.addInstance", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/addInstance".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetPoolsAddInstanceRequest) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to which instance_url is to be added. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolAddInstanceCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolAddInstanceCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolAddInstanceCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes instance URL from targetPool. +/// +/// A builder for the *removeInstance* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetPoolsRemoveInstanceRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetPoolsRemoveInstanceRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().remove_instance(&req, "project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolRemoveInstanceCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetPoolsRemoveInstanceRequest, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolRemoveInstanceCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolRemoveInstanceCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.removeInstance", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}/removeInstance".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetPoolsRemoveInstanceRequest) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn project(mut self, new_value: &str) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to which instance_url is to be removed. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolRemoveInstanceCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified TargetPool resource. +/// +/// A builder for the *delete* method supported by a *targetPool* resource. +/// It is not used directly, but through a `TargetPoolMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_pools().delete("project", "region", "targetPool") +/// .doit(); +/// # } +/// ``` +pub struct TargetPoolDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _target_pool: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetPoolDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetPoolDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetPools.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("targetPool", self._target_pool.to_string())); + for &field in ["alt", "project", "region", "targetPool"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/targetPools/{targetPool}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{targetPool}", "targetPool")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "targetPool"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetPoolDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> TargetPoolDeleteCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *target pool* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetPool resource to delete. + pub fn target_pool(mut self, new_value: &str) -> TargetPoolDeleteCall<'a, C, NC, A> { + self._target_pool = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetPoolDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetPoolDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetPoolDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of TargetInstance resources available to the specified project and zone. +/// +/// A builder for the *list* method supported by a *targetInstance* resource. +/// It is not used directly, but through a `TargetInstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_instances().list("project", "zone") +/// .page_token("amet.") +/// .max_results(83) +/// .filter("dolores") +/// .doit(); +/// # } +/// ``` +pub struct TargetInstanceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetInstanceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetInstanceList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetInstances.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/targetInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetInstanceListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> TargetInstanceListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> TargetInstanceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> TargetInstanceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> TargetInstanceListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetInstanceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetInstanceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetInstanceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a TargetInstance resource in the specified project and zone using the data included in the request. +/// +/// A builder for the *insert* method supported by a *targetInstance* resource. +/// It is not used directly, but through a `TargetInstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetInstance; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetInstance = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_instances().insert(&req, "project", "zone") +/// .doit(); +/// # } +/// ``` +pub struct TargetInstanceInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetInstance, + _project: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetInstanceInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetInstances.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + for &field in ["alt", "project", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/targetInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetInstance) -> TargetInstanceInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetInstanceInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> TargetInstanceInsertCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetInstanceInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetInstanceInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetInstanceInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of target instances grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *targetInstance* resource. +/// It is not used directly, but through a `TargetInstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_instances().aggregated_list("project") +/// .page_token("aliquyam") +/// .max_results(10) +/// .filter("sit") +/// .doit(); +/// # } +/// ``` +pub struct TargetInstanceAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetInstanceAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetInstanceAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetInstances.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/targetInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetInstanceAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetInstanceAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetInstanceAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified TargetInstance resource. +/// +/// A builder for the *get* method supported by a *targetInstance* resource. +/// It is not used directly, but through a `TargetInstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_instances().get("project", "zone", "targetInstance") +/// .doit(); +/// # } +/// ``` +pub struct TargetInstanceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _target_instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetInstanceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetInstance)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetInstances.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("targetInstance", self._target_instance.to_string())); + for &field in ["alt", "project", "zone", "targetInstance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/targetInstances/{targetInstance}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{targetInstance}", "targetInstance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "targetInstance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetInstanceGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> TargetInstanceGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *target instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetInstance resource to return. + pub fn target_instance(mut self, new_value: &str) -> TargetInstanceGetCall<'a, C, NC, A> { + self._target_instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetInstanceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetInstanceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetInstanceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified TargetInstance resource. +/// +/// A builder for the *delete* method supported by a *targetInstance* resource. +/// It is not used directly, but through a `TargetInstanceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_instances().delete("project", "zone", "targetInstance") +/// .doit(); +/// # } +/// ``` +pub struct TargetInstanceDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _target_instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetInstanceDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetInstanceDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetInstances.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("targetInstance", self._target_instance.to_string())); + for &field in ["alt", "project", "zone", "targetInstance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/targetInstances/{targetInstance}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{targetInstance}", "targetInstance")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "targetInstance"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetInstanceDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> TargetInstanceDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *target instance* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetInstance resource to delete. + pub fn target_instance(mut self, new_value: &str) -> TargetInstanceDeleteCall<'a, C, NC, A> { + self._target_instance = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetInstanceDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetInstanceDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetInstanceDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified ForwardingRule resource. +/// +/// A builder for the *get* method supported by a *globalForwardingRule* resource. +/// It is not used directly, but through a `GlobalForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_forwarding_rules().get("project", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct GlobalForwardingRuleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalForwardingRuleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ForwardingRule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalForwardingRules.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules/{forwardingRule}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> GlobalForwardingRuleGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource to return. + pub fn forwarding_rule(mut self, new_value: &str) -> GlobalForwardingRuleGetCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalForwardingRuleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalForwardingRuleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalForwardingRuleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified ForwardingRule resource. +/// +/// A builder for the *delete* method supported by a *globalForwardingRule* resource. +/// It is not used directly, but through a `GlobalForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_forwarding_rules().delete("project", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct GlobalForwardingRuleDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalForwardingRuleDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalForwardingRules.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules/{forwardingRule}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource to delete. + pub fn forwarding_rule(mut self, new_value: &str) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalForwardingRuleDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Changes target url for forwarding rule. +/// +/// A builder for the *setTarget* method supported by a *globalForwardingRule* resource. +/// It is not used directly, but through a `GlobalForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_forwarding_rules().set_target(&req, "project", "forwardingRule") +/// .doit(); +/// # } +/// ``` +pub struct GlobalForwardingRuleSetTargetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetReference, + _project: String, + _forwarding_rule: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalForwardingRuleSetTargetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalForwardingRules.setTarget", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("forwardingRule", self._forwarding_rule.to_string())); + for &field in ["alt", "project", "forwardingRule"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules/{forwardingRule}/setTarget".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{forwardingRule}", "forwardingRule")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "forwardingRule"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetReference) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *forwarding rule* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the ForwardingRule resource in which target is to be set. + pub fn forwarding_rule(mut self, new_value: &str) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> { + self._forwarding_rule = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalForwardingRuleSetTargetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a ForwardingRule resource in the specified project and region using the data included in the request. +/// +/// A builder for the *insert* method supported by a *globalForwardingRule* resource. +/// It is not used directly, but through a `GlobalForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::ForwardingRule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ForwardingRule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_forwarding_rules().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct GlobalForwardingRuleInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: ForwardingRule, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalForwardingRuleInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalForwardingRules.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ForwardingRule) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalForwardingRuleInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of ForwardingRule resources available to the specified project. +/// +/// A builder for the *list* method supported by a *globalForwardingRule* resource. +/// It is not used directly, but through a `GlobalForwardingRuleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.global_forwarding_rules().list("project") +/// .page_token("sadipscing") +/// .max_results(96) +/// .filter("sed") +/// .doit(); +/// # } +/// ``` +pub struct GlobalForwardingRuleListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for GlobalForwardingRuleListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> GlobalForwardingRuleListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ForwardingRuleList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.globalForwardingRules.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/forwardingRules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalForwardingRuleListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalForwardingRuleListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalForwardingRuleListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of image resources available to the specified project. +/// +/// A builder for the *list* method supported by a *image* resource. +/// It is not used directly, but through a `ImageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.images().list("project") +/// .page_token("dolore") +/// .max_results(77) +/// .filter("At") +/// .doit(); +/// # } +/// ``` +pub struct ImageListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ImageListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ImageList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.images.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/images".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ImageListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ImageListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> ImageListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> ImageListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ImageListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ImageListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ImageListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified image resource. +/// +/// A builder for the *delete* method supported by a *image* resource. +/// It is not used directly, but through a `ImageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.images().delete("project", "image") +/// .doit(); +/// # } +/// ``` +pub struct ImageDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _image: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ImageDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.images.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("image", self._image.to_string())); + for &field in ["alt", "project", "image"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/images/{image}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{image}", "image")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "image"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ImageDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *image* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the image resource to delete. + pub fn image(mut self, new_value: &str) -> ImageDeleteCall<'a, C, NC, A> { + self._image = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ImageDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ImageDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ImageDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets the deprecation status of an image. +/// +/// If an empty request body is given, clears the deprecation status instead. +/// +/// A builder for the *deprecate* method supported by a *image* resource. +/// It is not used directly, but through a `ImageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::DeprecationStatus; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DeprecationStatus = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.images().deprecate(&req, "project", "image") +/// .doit(); +/// # } +/// ``` +pub struct ImageDeprecateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: DeprecationStatus, + _project: String, + _image: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ImageDeprecateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageDeprecateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.images.deprecate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("image", self._image.to_string())); + for &field in ["alt", "project", "image"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/images/{image}/deprecate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{image}", "image")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "image"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DeprecationStatus) -> ImageDeprecateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ImageDeprecateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *image* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Image name. + pub fn image(mut self, new_value: &str) -> ImageDeprecateCall<'a, C, NC, A> { + self._image = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ImageDeprecateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ImageDeprecateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ImageDeprecateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an image resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *image* resource. +/// It is not used directly, but through a `ImageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Image; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Image = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.images().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ImageInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Image, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ImageInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.images.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/images".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Image) -> ImageInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ImageInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ImageInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ImageInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ImageInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified image resource. +/// +/// A builder for the *get* method supported by a *image* resource. +/// It is not used directly, but through a `ImageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.images().get("project", "image") +/// .doit(); +/// # } +/// ``` +pub struct ImageGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _image: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ImageGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ImageGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Image)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.images.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("image", self._image.to_string())); + for &field in ["alt", "project", "image"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/images/{image}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{image}", "image")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "image"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ImageGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *image* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the image resource to return. + pub fn image(mut self, new_value: &str) -> ImageGetCall<'a, C, NC, A> { + self._image = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ImageGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ImageGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ImageGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of machine type resources grouped by scope. +/// +/// A builder for the *aggregatedList* method supported by a *machineType* resource. +/// It is not used directly, but through a `MachineTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.machine_types().aggregated_list("project") +/// .page_token("et") +/// .max_results(37) +/// .filter("sed") +/// .doit(); +/// # } +/// ``` +pub struct MachineTypeAggregatedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MachineTypeAggregatedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MachineTypeAggregatedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MachineTypeAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.machineTypes.aggregatedList", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/machineTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MachineTypeAggregatedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MachineTypeAggregatedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MachineTypeAggregatedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified machine type resource. +/// +/// A builder for the *get* method supported by a *machineType* resource. +/// It is not used directly, but through a `MachineTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.machine_types().get("project", "zone", "machineType") +/// .doit(); +/// # } +/// ``` +pub struct MachineTypeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _machine_type: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MachineTypeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MachineTypeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MachineType)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.machineTypes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("machineType", self._machine_type.to_string())); + for &field in ["alt", "project", "zone", "machineType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes/{machineType}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{machineType}", "machineType")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "machineType"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> MachineTypeGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> MachineTypeGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *machine type* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the machine type resource to return. + pub fn machine_type(mut self, new_value: &str) -> MachineTypeGetCall<'a, C, NC, A> { + self._machine_type = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MachineTypeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MachineTypeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MachineTypeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of machine type resources available to the specified project. +/// +/// A builder for the *list* method supported by a *machineType* resource. +/// It is not used directly, but through a `MachineTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.machine_types().list("project", "zone") +/// .page_token("takimata") +/// .max_results(48) +/// .filter("labore") +/// .doit(); +/// # } +/// ``` +pub struct MachineTypeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MachineTypeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MachineTypeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MachineTypeList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.machineTypes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> MachineTypeListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the zone for this request. + pub fn zone(mut self, new_value: &str) -> MachineTypeListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> MachineTypeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> MachineTypeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> MachineTypeListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MachineTypeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MachineTypeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MachineTypeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Moves a persistent disk from one zone to another. +/// +/// A builder for the *moveDisk* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::DiskMoveRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DiskMoveRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().move_disk(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectMoveDiskCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: DiskMoveRequest, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectMoveDiskCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMoveDiskCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.projects.moveDisk", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/moveDisk".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DiskMoveRequest) -> ProjectMoveDiskCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ProjectMoveDiskCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMoveDiskCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectMoveDiskCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectMoveDiskCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Sets metadata common to all instances within the specified project using the data included in the request. +/// +/// A builder for the *setCommonInstanceMetadata* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Metadata; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Metadata = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().set_common_instance_metadata(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Metadata, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.projects.setCommonInstanceMetadata", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/setCommonInstanceMetadata".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Metadata) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSetCommonInstanceMetadataCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified project resource. +/// +/// A builder for the *get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().get("project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Project)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.projects.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ProjectGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Moves an instance and its attached persistent disks from one zone to another. +/// +/// A builder for the *moveInstance* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::InstanceMoveRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InstanceMoveRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().move_instance(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectMoveInstanceCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceMoveRequest, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectMoveInstanceCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMoveInstanceCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.projects.moveInstance", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/moveInstance".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InstanceMoveRequest) -> ProjectMoveInstanceCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ProjectMoveInstanceCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMoveInstanceCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectMoveInstanceCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectMoveInstanceCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Enables the usage export feature and sets the usage export bucket where reports are stored. If you provide an empty request body using this method, the usage export feature will be disabled. +/// +/// A builder for the *setUsageExportBucket* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UsageExportLocation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UsageExportLocation = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().set_usage_export_bucket(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSetUsageExportBucketCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UsageExportLocation, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectSetUsageExportBucketCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectSetUsageExportBucketCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.projects.setUsageExportBucket", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/setUsageExportBucket".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UsageExportLocation) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSetUsageExportBucketCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified HttpHealthCheck resource. +/// +/// A builder for the *get* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().get("project", "httpHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _http_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, HttpHealthCheck)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("httpHealthCheck", self._http_health_check.to_string())); + for &field in ["alt", "project", "httpHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks/{httpHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpHealthCheck}", "httpHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "httpHealthCheck"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *http health check* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the HttpHealthCheck resource to return. + pub fn http_health_check(mut self, new_value: &str) -> HttpHealthCheckGetCall<'a, C, NC, A> { + self._http_health_check = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a HttpHealthCheck resource in the specified project using the data included in the request. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::HttpHealthCheck; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: HttpHealthCheck = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().patch(&req, "project", "httpHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpHealthCheck, + _project: String, + _http_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("httpHealthCheck", self._http_health_check.to_string())); + for &field in ["alt", "project", "httpHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks/{httpHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpHealthCheck}", "httpHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "httpHealthCheck"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &HttpHealthCheck) -> HttpHealthCheckPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckPatchCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *http health check* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the HttpHealthCheck resource to update. + pub fn http_health_check(mut self, new_value: &str) -> HttpHealthCheckPatchCall<'a, C, NC, A> { + self._http_health_check = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of HttpHealthCheck resources available to the specified project. +/// +/// A builder for the *list* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().list("project") +/// .page_token("labore") +/// .max_results(73) +/// .filter("takimata") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, HttpHealthCheckList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> HttpHealthCheckListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> HttpHealthCheckListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> HttpHealthCheckListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified HttpHealthCheck resource. +/// +/// A builder for the *delete* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().delete("project", "httpHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _http_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("httpHealthCheck", self._http_health_check.to_string())); + for &field in ["alt", "project", "httpHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks/{httpHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpHealthCheck}", "httpHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "httpHealthCheck"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *http health check* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the HttpHealthCheck resource to delete. + pub fn http_health_check(mut self, new_value: &str) -> HttpHealthCheckDeleteCall<'a, C, NC, A> { + self._http_health_check = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a HttpHealthCheck resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::HttpHealthCheck; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: HttpHealthCheck = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpHealthCheck, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &HttpHealthCheck) -> HttpHealthCheckInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a HttpHealthCheck resource in the specified project using the data included in the request. +/// +/// A builder for the *update* method supported by a *httpHealthCheck* resource. +/// It is not used directly, but through a `HttpHealthCheckMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::HttpHealthCheck; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: HttpHealthCheck = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.http_health_checks().update(&req, "project", "httpHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpHealthCheckUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpHealthCheck, + _project: String, + _http_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for HttpHealthCheckUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> HttpHealthCheckUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.httpHealthChecks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("httpHealthCheck", self._http_health_check.to_string())); + for &field in ["alt", "project", "httpHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/httpHealthChecks/{httpHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpHealthCheck}", "httpHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "httpHealthCheck"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &HttpHealthCheck) -> HttpHealthCheckUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> HttpHealthCheckUpdateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *http health check* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the HttpHealthCheck resource to update. + pub fn http_health_check(mut self, new_value: &str) -> HttpHealthCheckUpdateCall<'a, C, NC, A> { + self._http_health_check = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpHealthCheckUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpHealthCheckUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpHealthCheckUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified instance template resource. +/// +/// A builder for the *delete* method supported by a *instanceTemplate* resource. +/// It is not used directly, but through a `InstanceTemplateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instance_templates().delete("project", "instanceTemplate") +/// .doit(); +/// # } +/// ``` +pub struct InstanceTemplateDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _instance_template: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceTemplateDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceTemplateDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instanceTemplates.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("instanceTemplate", self._instance_template.to_string())); + for &field in ["alt", "project", "instanceTemplate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates/{instanceTemplate}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{instanceTemplate}", "instanceTemplate")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "instanceTemplate"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> InstanceTemplateDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *instance template* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance template resource to delete. + pub fn instance_template(mut self, new_value: &str) -> InstanceTemplateDeleteCall<'a, C, NC, A> { + self._instance_template = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceTemplateDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceTemplateDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceTemplateDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified instance template resource. +/// +/// A builder for the *get* method supported by a *instanceTemplate* resource. +/// It is not used directly, but through a `InstanceTemplateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instance_templates().get("project", "instanceTemplate") +/// .doit(); +/// # } +/// ``` +pub struct InstanceTemplateGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _instance_template: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceTemplateGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceTemplateGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceTemplate)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instanceTemplates.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("instanceTemplate", self._instance_template.to_string())); + for &field in ["alt", "project", "instanceTemplate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates/{instanceTemplate}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{instanceTemplate}", "instanceTemplate")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "instanceTemplate"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> InstanceTemplateGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *instance template* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the instance template resource to return. + pub fn instance_template(mut self, new_value: &str) -> InstanceTemplateGetCall<'a, C, NC, A> { + self._instance_template = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceTemplateGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceTemplateGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceTemplateGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of instance template resources contained within the specified project. +/// +/// A builder for the *list* method supported by a *instanceTemplate* resource. +/// It is not used directly, but through a `InstanceTemplateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instance_templates().list("project") +/// .page_token("et") +/// .max_results(5) +/// .filter("sea") +/// .doit(); +/// # } +/// ``` +pub struct InstanceTemplateListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceTemplateListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceTemplateListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceTemplateList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instanceTemplates.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> InstanceTemplateListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> InstanceTemplateListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> InstanceTemplateListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> InstanceTemplateListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceTemplateListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceTemplateListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceTemplateListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates an instance template resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *instanceTemplate* resource. +/// It is not used directly, but through a `InstanceTemplateMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::InstanceTemplate; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InstanceTemplate = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.instance_templates().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct InstanceTemplateInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceTemplate, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InstanceTemplateInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InstanceTemplateInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.instanceTemplates.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InstanceTemplate) -> InstanceTemplateInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> InstanceTemplateInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceTemplateInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceTemplateInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceTemplateInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified TargetHttpProxy resource. +/// +/// A builder for the *delete* method supported by a *targetHttpProxy* resource. +/// It is not used directly, but through a `TargetHttpProxyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_http_proxies().delete("project", "targetHttpProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpProxyDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _target_http_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetHttpProxyDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxyDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetHttpProxies.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("targetHttpProxy", self._target_http_proxy.to_string())); + for &field in ["alt", "project", "targetHttpProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/targetHttpProxies/{targetHttpProxy}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpProxy}", "targetHttpProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "targetHttpProxy"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetHttpProxyDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *target http proxy* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetHttpProxy resource to delete. + pub fn target_http_proxy(mut self, new_value: &str) -> TargetHttpProxyDeleteCall<'a, C, NC, A> { + self._target_http_proxy = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpProxyDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpProxyDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpProxyDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of TargetHttpProxy resources available to the specified project. +/// +/// A builder for the *list* method supported by a *targetHttpProxy* resource. +/// It is not used directly, but through a `TargetHttpProxyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_http_proxies().list("project") +/// .page_token("sea") +/// .max_results(25) +/// .filter("dolores") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpProxyListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetHttpProxyListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxyListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetHttpProxyList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetHttpProxies.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/targetHttpProxies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetHttpProxyListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> TargetHttpProxyListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> TargetHttpProxyListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> TargetHttpProxyListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpProxyListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpProxyListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpProxyListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified TargetHttpProxy resource. +/// +/// A builder for the *get* method supported by a *targetHttpProxy* resource. +/// It is not used directly, but through a `TargetHttpProxyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_http_proxies().get("project", "targetHttpProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpProxyGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _target_http_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetHttpProxyGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxyGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetHttpProxy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetHttpProxies.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("targetHttpProxy", self._target_http_proxy.to_string())); + for &field in ["alt", "project", "targetHttpProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/targetHttpProxies/{targetHttpProxy}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpProxy}", "targetHttpProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "targetHttpProxy"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetHttpProxyGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *target http proxy* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetHttpProxy resource to return. + pub fn target_http_proxy(mut self, new_value: &str) -> TargetHttpProxyGetCall<'a, C, NC, A> { + self._target_http_proxy = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpProxyGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpProxyGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpProxyGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Changes the URL map for TargetHttpProxy. +/// +/// A builder for the *setUrlMap* method supported by a *targetHttpProxy* resource. +/// It is not used directly, but through a `TargetHttpProxyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::UrlMapReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UrlMapReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_http_proxies().set_url_map(&req, "project", "targetHttpProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpProxySetUrlMapCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMapReference, + _project: String, + _target_http_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetHttpProxySetUrlMapCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxySetUrlMapCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetHttpProxies.setUrlMap", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("targetHttpProxy", self._target_http_proxy.to_string())); + for &field in ["alt", "project", "targetHttpProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/targetHttpProxies/{targetHttpProxy}/setUrlMap".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpProxy}", "targetHttpProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "targetHttpProxy"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UrlMapReference) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *target http proxy* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the TargetHttpProxy resource whose URL map is to be set. + pub fn target_http_proxy(mut self, new_value: &str) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> { + self._target_http_proxy = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpProxySetUrlMapCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a TargetHttpProxy resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *targetHttpProxy* resource. +/// It is not used directly, but through a `TargetHttpProxyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::TargetHttpProxy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: TargetHttpProxy = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.target_http_proxies().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpProxyInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetHttpProxy, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TargetHttpProxyInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TargetHttpProxyInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.targetHttpProxies.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/targetHttpProxies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &TargetHttpProxy) -> TargetHttpProxyInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> TargetHttpProxyInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpProxyInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpProxyInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpProxyInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified zone-specific operation resource. +/// +/// A builder for the *delete* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().delete("project", "zone", "operation") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.zoneOperations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["project", "zone", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to delete. + pub fn operation(mut self, new_value: &str) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of operation resources contained within the specified zone. +/// +/// A builder for the *list* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().list("project", "zone") +/// .page_token("kasd") +/// .max_results(64) +/// .filter("sadipscing") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.zoneOperations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "zone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> ZoneOperationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the specified zone-specific operation resource. +/// +/// A builder for the *get* method supported by a *zoneOperation* resource. +/// It is not used directly, but through a `ZoneOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.zone_operations().get("project", "zone", "operation") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ZoneOperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ZoneOperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.zoneOperations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("zone", self._zone.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["alt", "project", "zone", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "zone", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn zone(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._zone = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to return. + pub fn operation(mut self, new_value: &str) -> ZoneOperationGetCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified route resource. +/// +/// A builder for the *get* method supported by a *route* resource. +/// It is not used directly, but through a `RouteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.routes().get("project", "route") +/// .doit(); +/// # } +/// ``` +pub struct RouteGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _route: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RouteGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RouteGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Route)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.routes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("route", self._route.to_string())); + for &field in ["alt", "project", "route"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/routes/{route}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{route}", "route")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "route"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> RouteGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *route* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the route resource to return. + pub fn route(mut self, new_value: &str) -> RouteGetCall<'a, C, NC, A> { + self._route = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RouteGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RouteGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RouteGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a route resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *route* resource. +/// It is not used directly, but through a `RouteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Route; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Route = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.routes().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct RouteInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Route, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RouteInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RouteInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.routes.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/routes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Route) -> RouteInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> RouteInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RouteInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RouteInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RouteInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of route resources available to the specified project. +/// +/// A builder for the *list* method supported by a *route* resource. +/// It is not used directly, but through a `RouteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.routes().list("project") +/// .page_token("kasd") +/// .max_results(31) +/// .filter("et") +/// .doit(); +/// # } +/// ``` +pub struct RouteListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RouteListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RouteListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RouteList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.routes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/routes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> RouteListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> RouteListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> RouteListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> RouteListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RouteListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RouteListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RouteListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified route resource. +/// +/// A builder for the *delete* method supported by a *route* resource. +/// It is not used directly, but through a `RouteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.routes().delete("project", "route") +/// .doit(); +/// # } +/// ``` +pub struct RouteDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _route: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RouteDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RouteDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.routes.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("route", self._route.to_string())); + for &field in ["alt", "project", "route"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/routes/{route}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{route}", "route")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "route"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the project scoping this request. + pub fn project(mut self, new_value: &str) -> RouteDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *route* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the route resource to delete. + pub fn route(mut self, new_value: &str) -> RouteDeleteCall<'a, C, NC, A> { + self._route = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RouteDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RouteDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RouteDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the specified firewall resource with the data included in the request. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Firewall; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Firewall = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().patch(&req, "project", "firewall") +/// .doit(); +/// # } +/// ``` +pub struct FirewallPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Firewall, + _project: String, + _firewall: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("firewall", self._firewall.to_string())); + for &field in ["alt", "project", "firewall"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls/{firewall}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{firewall}", "firewall")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "firewall"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Firewall) -> FirewallPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallPatchCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *firewall* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the firewall resource to update. + pub fn firewall(mut self, new_value: &str) -> FirewallPatchCall<'a, C, NC, A> { + self._firewall = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the specified firewall resource. +/// +/// A builder for the *get* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().get("project", "firewall") +/// .doit(); +/// # } +/// ``` +pub struct FirewallGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _firewall: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Firewall)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("firewall", self._firewall.to_string())); + for &field in ["alt", "project", "firewall"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls/{firewall}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{firewall}", "firewall")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "firewall"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *firewall* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the firewall resource to return. + pub fn firewall(mut self, new_value: &str) -> FirewallGetCall<'a, C, NC, A> { + self._firewall = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a firewall resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Firewall; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Firewall = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct FirewallInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Firewall, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Firewall) -> FirewallInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the specified firewall resource with the data included in the request. +/// +/// A builder for the *update* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// use compute1::Firewall; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Firewall = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().update(&req, "project", "firewall") +/// .doit(); +/// # } +/// ``` +pub struct FirewallUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _request: Firewall, + _project: String, + _firewall: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("firewall", self._firewall.to_string())); + for &field in ["alt", "project", "firewall"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls/{firewall}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{firewall}", "firewall")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "firewall"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Firewall) -> FirewallUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallUpdateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *firewall* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the firewall resource to update. + pub fn firewall(mut self, new_value: &str) -> FirewallUpdateCall<'a, C, NC, A> { + self._firewall = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified firewall resource. +/// +/// A builder for the *delete* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().delete("project", "firewall") +/// .doit(); +/// # } +/// ``` +pub struct FirewallDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _firewall: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("firewall", self._firewall.to_string())); + for &field in ["alt", "project", "firewall"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls/{firewall}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{firewall}", "firewall")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "firewall"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *firewall* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the firewall resource to delete. + pub fn firewall(mut self, new_value: &str) -> FirewallDeleteCall<'a, C, NC, A> { + self._firewall = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of firewall resources available to the specified project. +/// +/// A builder for the *list* method supported by a *firewall* resource. +/// It is not used directly, but through a `FirewallMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.firewalls().list("project") +/// .page_token("sed") +/// .max_results(25) +/// .filter("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct FirewallListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FirewallListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FirewallListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FirewallList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.firewalls.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/global/firewalls".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> FirewallListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> FirewallListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> FirewallListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> FirewallListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FirewallListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FirewallListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FirewallListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of operation resources contained within the specified region. +/// +/// A builder for the *list* method supported by a *regionOperation* resource. +/// It is not used directly, but through a `RegionOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.region_operations().list("project", "region") +/// .page_token("sea") +/// .max_results(51) +/// .filter("labore") +/// .doit(); +/// # } +/// ``` +pub struct RegionOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.regionOperations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "region", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "region"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> RegionOperationListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> RegionOperationListCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> RegionOperationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + pub fn max_results(mut self, new_value: u32) -> RegionOperationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Optional. Filter expression for filtering listed resources. + pub fn filter(mut self, new_value: &str) -> RegionOperationListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the specified region-specific operation resource. +/// +/// A builder for the *delete* method supported by a *regionOperation* resource. +/// It is not used directly, but through a `RegionOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.region_operations().delete("project", "region", "operation") +/// .doit(); +/// # } +/// ``` +pub struct RegionOperationDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionOperationDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionOperationDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.regionOperations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["project", "region", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> RegionOperationDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the region scoping this request. + pub fn region(mut self, new_value: &str) -> RegionOperationDeleteCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to delete. + pub fn operation(mut self, new_value: &str) -> RegionOperationDeleteCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionOperationDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionOperationDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the specified region-specific operation resource. +/// +/// A builder for the *get* method supported by a *regionOperation* resource. +/// It is not used directly, but through a `RegionOperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-compute1" as compute1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use compute1::Compute; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Compute::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.region_operations().get("project", "region", "operation") +/// .doit(); +/// # } +/// ``` +pub struct RegionOperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionOperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionOperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "compute.regionOperations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("region", self._region.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["alt", "project", "region", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "region", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Project ID for this request. + pub fn project(mut self, new_value: &str) -> RegionOperationGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *region* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the zone scoping this request. + pub fn region(mut self, new_value: &str) -> RegionOperationGetCall<'a, C, NC, A> { + self._region = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Name of the operation resource to return. + pub fn operation(mut self, new_value: &str) -> RegionOperationGetCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionOperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionOperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionOperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/container1_beta1/Cargo.toml b/gen/container1_beta1/Cargo.toml new file mode 100644 index 0000000000..3ca3bc856d --- /dev/null +++ b/gen/container1_beta1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-container1_beta1" +version = "0.1.0+20150223" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with container (protocol v1beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/container1_beta1" +homepage = "https://cloud.google.com/container-engine/docs/v1beta1/" +documentation = "http://byron.github.io/google-apis-rs/google-container1_beta1" +license = "MIT" +keywords = ["container", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/container1_beta1/LICENSE.md b/gen/container1_beta1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/container1_beta1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/container1_beta1/README.md b/gen/container1_beta1/README.md new file mode 100644 index 0000000000..15d5dcddf8 --- /dev/null +++ b/gen/container1_beta1/README.md @@ -0,0 +1,165 @@ + +The `google-container1_beta1` library allows access to all features of the *Google container* service. + +This documentation was generated from *container* crate version *0.1.0+20150223*, where *20150223* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *container* *v1_beta1* API can be found at the +[official documentation site](https://cloud.google.com/container-engine/docs/v1beta1/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.Container.html) ... + +* projects + * [*clusters list*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectClusterListCall.html), [*operations list*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectOperationListCall.html), [*zones clusters create*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneClusterCreateCall.html), [*zones clusters delete*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneClusterDeleteCall.html), [*zones clusters get*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneClusterGetCall.html), [*zones clusters list*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneClusterListCall.html), [*zones operations get*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneOperationGetCall.html) and [*zones operations list*](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.ProjectZoneOperationListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-container1_beta1/struct.Container.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.projects().zones_operations_get(...).doit() +let r = hub.projects().zones_clusters_delete(...).doit() +let r = hub.projects().zones_clusters_create(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-container1_beta1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-container1_beta1" as container1_beta1; +use container1_beta1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use container1_beta1::Container; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Container::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.projects().zones_operations_get("projectId", "zoneId", "operationId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-container1_beta1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-container1_beta1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-container1_beta1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-container1_beta1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **container1_beta1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/container1_beta1/src/cmn.rs b/gen/container1_beta1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/container1_beta1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/container1_beta1/src/lib.rs b/gen/container1_beta1/src/lib.rs new file mode 100644 index 0000000000..d9bfbf419a --- /dev/null +++ b/gen/container1_beta1/src/lib.rs @@ -0,0 +1,2732 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *container* crate version *0.1.0+20150223*, where *20150223* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *container* *v1_beta1* API can be found at the +//! [official documentation site](https://cloud.google.com/container-engine/docs/v1beta1/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/container1_beta1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Container.html) ... +//! +//! * projects +//! * [*clusters list*](struct.ProjectClusterListCall.html), [*operations list*](struct.ProjectOperationListCall.html), [*zones clusters create*](struct.ProjectZoneClusterCreateCall.html), [*zones clusters delete*](struct.ProjectZoneClusterDeleteCall.html), [*zones clusters get*](struct.ProjectZoneClusterGetCall.html), [*zones clusters list*](struct.ProjectZoneClusterListCall.html), [*zones operations get*](struct.ProjectZoneOperationGetCall.html) and [*zones operations list*](struct.ProjectZoneOperationListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Container.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.projects().zones_operations_get(...).doit() +//! let r = hub.projects().zones_clusters_delete(...).doit() +//! let r = hub.projects().zones_clusters_create(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-container1_beta1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-container1_beta1" as container1_beta1; +//! use container1_beta1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use container1_beta1::Container; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Container::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.projects().zones_operations_get("projectId", "zoneId", "operationId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your data across Google Cloud Platform services + CloudPlatform, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::CloudPlatform + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Container related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-container1_beta1" as container1_beta1; +/// use container1_beta1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use container1_beta1::Container; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_operations_get("projectId", "zoneId", "operationId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Container { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Container {} + +impl<'a, C, NC, A> Container + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Container { + Container { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn projects(&'a self) -> ProjectMethods<'a, C, NC, A> { + ProjectMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [zones operations list projects](struct.ProjectZoneOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListOperationsResponse { + /// A list of operations in the project in the specified zone. + pub operations: Vec, +} + +impl ResponseResult for ListOperationsResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [clusters list projects](struct.ProjectClusterListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListAggregatedClustersResponse { + /// A list of clusters in the project, across all zones. + pub clusters: Vec, +} + +impl ResponseResult for ListAggregatedClustersResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [zones clusters list projects](struct.ProjectZoneClusterListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListClustersResponse { + /// A list of clusters in the project in the specified zone. + pub clusters: Vec, +} + +impl ResponseResult for ListClustersResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MasterAuth { + /// The password to use when accessing the Kubernetes master endpoint. + pub password: String, + /// The username to use when accessing the Kubernetes master endpoint. + pub user: String, +} + +impl Part for MasterAuth {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [zones clusters get projects](struct.ProjectZoneClusterGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Cluster { + /// [Output only] The current status of this cluster. + pub status: String, + /// [Output only] The IP addresses of the container pods in this cluster, in CIDR notation (e.g. 1.2.3.4/29). + #[serde(alias="containerIpv4Cidr")] + pub container_ipv4_cidr: String, + /// An optional description of this cluster. + pub description: String, + /// [Output only] The size of the address space on each node for hosting containers. + #[serde(alias="nodeRoutingPrefixSize")] + pub node_routing_prefix_size: i32, + /// The HTTP basic authentication information for accessing the master. Because the master endpoint is open to the internet, you should create a strong password. + #[serde(alias="masterAuth")] + pub master_auth: MasterAuth, + /// The API version of the Kubernetes master and kubelets running in this cluster. Leave blank to pick up the latest stable release, or specify a version of the form "x.y.z". The Google Container Engine release notes lists the currently supported versions. If an incorrect version is specified, the server returns an error listing the currently supported versions. + #[serde(alias="clusterApiVersion")] + pub cluster_api_version: String, + /// [Output only] The time the cluster was created, in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// The name of this cluster. The name must be unique within this project and zone, and can be up to 40 characters with the following restrictions: + /// - Lowercase letters, numbers, and hyphens only. + /// - Must start with a letter. + /// - Must end with a number or a letter. + pub name: String, + /// [Output only] The IP address of this cluster's Kubernetes master. The endpoint can be accessed from the internet at https://username:password@endpoint/. + /// + /// See the masterAuth property of this resource for username and password information. + pub endpoint: String, + /// The name of the Google Compute Engine network to which the cluster is connected. + pub network: String, + /// [Output only] The name of the Google Compute Engine zone in which the cluster resides. + pub zone: String, + /// The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances plus one (to include the master). You must also have available firewall and routes quota. + #[serde(alias="numNodes")] + pub num_nodes: i32, + /// The machine type and image to use for all nodes in this cluster. See the descriptions of the child properties of nodeConfig. + #[serde(alias="nodeConfig")] + pub node_config: NodeConfig, + /// [Output only] Server-defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output only] Additional information about the current status of this cluster, if available. + #[serde(alias="statusMessage")] + pub status_message: String, + /// [Output only] The IP addresses of the Kubernetes services in this cluster, in CIDR notation (e.g. 1.2.3.4/29). Service addresses are always in the 10.0.0.0/16 range. + #[serde(alias="servicesIpv4Cidr")] + pub services_ipv4_cidr: String, +} + +impl ResponseResult for Cluster {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct NodeConfig { + /// The optional list of ServiceAccounts, each with their specified scopes, to be made available on all of the node VMs. In addition to the service accounts and scopes specified, the "default" account will always be created with the following scopes to ensure the correct functioning of the cluster: + /// - https://www.googleapis.com/auth/compute, + /// - https://www.googleapis.com/auth/devstorage.read_only + #[serde(alias="serviceAccounts")] + pub service_accounts: Vec, + /// The name of a Google Compute Engine machine type (e.g. n1-standard-1). + /// + /// If unspecified, the default machine type is n1-standard-1. + #[serde(alias="machineType")] + pub machine_type: String, + /// The fully-specified name of a Google Compute Engine image. For example: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-vYYYYMMDD (where YYYMMDD is the version date). + /// + /// If specifying an image, you are responsible for ensuring its compatibility with the Debian 7 backports image. We recommend leaving this field blank to accept the default backports-debian-7-wheezy value. + #[serde(alias="sourceImage")] + pub source_image: String, +} + +impl Part for NodeConfig {} + + +/// A Compute Engine service account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ServiceAccount { + /// The list of scopes to be made available for this service account. + pub scopes: Vec, + /// Email address of the service account. + pub email: String, +} + +impl Part for ServiceAccount {} + + +/// Defines the operation resource. All fields are output only. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [zones operations get projects](struct.ProjectZoneOperationGetCall.html) (response) +/// * [zones clusters delete projects](struct.ProjectZoneClusterDeleteCall.html) (response) +/// * [zones clusters create projects](struct.ProjectZoneClusterCreateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Operation { + /// The current status of the operation. + pub status: String, + /// The server-assigned ID for this operation. If the operation is fulfilled upfront, it may not have a resource name. + pub name: String, + /// The name of the Google Compute Engine zone in which the operation is taking place. + pub zone: String, + /// If an error has occurred, a textual description of the error. + #[serde(alias="errorMessage")] + pub error_message: String, + /// Server-defined URL for the target of the operation. + #[serde(alias="targetLink")] + pub target_link: String, + /// The operation type. + #[serde(alias="operationType")] + pub operation_type: String, + /// Server-defined URL for the resource. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Optional] The URL of the cluster resource that this operation is associated with. + pub target: String, +} + +impl ResponseResult for Operation {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [operations list projects](struct.ProjectOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListAggregatedOperationsResponse { + /// A list of operations in the project, across all zones. + pub operations: Vec, +} + +impl ResponseResult for ListAggregatedOperationsResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [zones clusters create projects](struct.ProjectZoneClusterCreateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct CreateClusterRequest { + /// A cluster resource. + pub cluster: Option, +} + +impl RequestValue for CreateClusterRequest {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *project* resources. +/// It is not used directly, but through the `Container` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-container1_beta1" as container1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use container1_beta1::Container; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Container::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `clusters_list(...)`, `operations_list(...)`, `zones_clusters_create(...)`, `zones_clusters_delete(...)`, `zones_clusters_get(...)`, `zones_clusters_list(...)`, `zones_operations_get(...)` and `zones_operations_list(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProjectMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific cluster. + pub fn zones_clusters_get(&self, project_id: &str, zone_id: &str, cluster_id: &str) -> ProjectZoneClusterGetCall<'a, C, NC, A> { + ProjectZoneClusterGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _cluster_id: cluster_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all operations in a project, across all zones. + pub fn operations_list(&self, project_id: &str) -> ProjectOperationListCall<'a, C, NC, A> { + ProjectOperationListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the cluster, including the Kubernetes master and all worker nodes. + /// + /// Firewalls and routes that were configured at cluster creation are also deleted. + pub fn zones_clusters_delete(&self, project_id: &str, zone_id: &str, cluster_id: &str) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> { + ProjectZoneClusterDeleteCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _cluster_id: cluster_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all clusters owned by a project across all zones. + pub fn clusters_list(&self, project_id: &str) -> ProjectClusterListCall<'a, C, NC, A> { + ProjectClusterListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the specified operation. + pub fn zones_operations_get(&self, project_id: &str, zone_id: &str, operation_id: &str) -> ProjectZoneOperationGetCall<'a, C, NC, A> { + ProjectZoneOperationGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _operation_id: operation_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all operations in a project in a specific zone. + pub fn zones_operations_list(&self, project_id: &str, zone_id: &str) -> ProjectZoneOperationListCall<'a, C, NC, A> { + ProjectZoneOperationListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all clusters owned by a project in the specified zone. + pub fn zones_clusters_list(&self, project_id: &str, zone_id: &str) -> ProjectZoneClusterListCall<'a, C, NC, A> { + ProjectZoneClusterListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a cluster, consisting of the specified number and type of Google Compute Engine instances, plus a Kubernetes master instance. + /// + /// The cluster is created in the project's default network. + /// + /// A firewall is added that allows traffic into port 443 on the master, which enables HTTPS. A firewall and a route is added for each node to allow the containers on that node to communicate with all other instances in the cluster. + /// + /// Finally, a route named k8s-iproute-10-xx-0-0 is created to track that the cluster's 10.xx.0.0/16 CIDR has been assigned. + pub fn zones_clusters_create(&self, request: &CreateClusterRequest, project_id: &str, zone_id: &str) -> ProjectZoneClusterCreateCall<'a, C, NC, A> { + ProjectZoneClusterCreateCall { + hub: self.hub, + _request: request.clone(), + _project_id: project_id.to_string(), + _zone_id: zone_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Gets a specific cluster. +/// +/// A builder for the *zones.clusters.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_clusters_get("projectId", "zoneId", "clusterId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone_id: String, + _cluster_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneClusterGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneClusterGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Cluster)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.clusters.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + params.push(("clusterId", self._cluster_id.to_string())); + for &field in ["alt", "projectId", "zoneId", "clusterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/clusters/{clusterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId"), ("{clusterId}", "clusterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "zoneId", "clusterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterGetCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone in which the cluster resides. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneClusterGetCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *cluster id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the cluster to retrieve. + pub fn cluster_id(mut self, new_value: &str) -> ProjectZoneClusterGetCall<'a, C, NC, A> { + self._cluster_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneClusterGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all operations in a project, across all zones. +/// +/// A builder for the *operations.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().operations_list("projectId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListAggregatedOperationsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.operations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectOperationListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes the cluster, including the Kubernetes master and all worker nodes. +/// +/// Firewalls and routes that were configured at cluster creation are also deleted. +/// +/// A builder for the *zones.clusters.delete* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_clusters_delete("projectId", "zoneId", "clusterId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone_id: String, + _cluster_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneClusterDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneClusterDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.clusters.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + params.push(("clusterId", self._cluster_id.to_string())); + for &field in ["alt", "projectId", "zoneId", "clusterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/clusters/{clusterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId"), ("{clusterId}", "clusterId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "zoneId", "clusterId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone in which the cluster resides. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *cluster id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the cluster to delete. + pub fn cluster_id(mut self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> { + self._cluster_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneClusterDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all clusters owned by a project across all zones. +/// +/// A builder for the *clusters.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().clusters_list("projectId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectClusterListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectClusterListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectClusterListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListAggregatedClustersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.clusters.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/clusters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectClusterListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectClusterListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectClusterListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectClusterListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the specified operation. +/// +/// A builder for the *zones.operations.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_operations_get("projectId", "zoneId", "operationId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneOperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone_id: String, + _operation_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneOperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneOperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.operations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + params.push(("operationId", self._operation_id.to_string())); + for &field in ["alt", "projectId", "zoneId", "operationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/operations/{operationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId"), ("{operationId}", "operationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["projectId", "zoneId", "operationId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneOperationGetCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone in which the operation resides. This is always the same zone as the cluster with which the operation is associated. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneOperationGetCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *operation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The server-assigned name of the operation. + pub fn operation_id(mut self, new_value: &str) -> ProjectZoneOperationGetCall<'a, C, NC, A> { + self._operation_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneOperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneOperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all operations in a project in a specific zone. +/// +/// A builder for the *zones.operations.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_operations_list("projectId", "zoneId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneOperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneOperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneOperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListOperationsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.operations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + for &field in ["alt", "projectId", "zoneId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "zoneId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneOperationListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone to return operations for. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneOperationListCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneOperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneOperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all clusters owned by a project in the specified zone. +/// +/// A builder for the *zones.clusters.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_clusters_list("projectId", "zoneId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneClusterListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneClusterListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListClustersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.clusters.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + for &field in ["alt", "projectId", "zoneId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/clusters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "zoneId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterListCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone in which the cluster resides. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneClusterListCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneClusterListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a cluster, consisting of the specified number and type of Google Compute Engine instances, plus a Kubernetes master instance. +/// +/// The cluster is created in the project's default network. +/// +/// A firewall is added that allows traffic into port 443 on the master, which enables HTTPS. A firewall and a route is added for each node to allow the containers on that node to communicate with all other instances in the cluster. +/// +/// Finally, a route named k8s-iproute-10-xx-0-0 is created to track that the cluster's 10.xx.0.0/16 CIDR has been assigned. +/// +/// A builder for the *zones.clusters.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-container1_beta1" as container1_beta1; +/// use container1_beta1::CreateClusterRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1_beta1::Container; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Container::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreateClusterRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().zones_clusters_create(&req, "projectId", "zoneId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterCreateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Container, + _request: CreateClusterRequest, + _project_id: String, + _zone_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectZoneClusterCreateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectZoneClusterCreateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "container.projects.zones.clusters.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + params.push(("zoneId", self._zone_id.to_string())); + for &field in ["alt", "projectId", "zoneId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/container/v1beta1/projects/{projectId}/zones/{zoneId}/clusters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zoneId}", "zoneId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["projectId", "zoneId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreateClusterRequest) -> ProjectZoneClusterCreateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The Google Developers Console project ID or project number. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterCreateCall<'a, C, NC, A> { + self._project_id = new_value.to_string(); + self + } + /// Sets the *zone id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the Google Compute Engine zone in which the cluster resides. + pub fn zone_id(mut self, new_value: &str) -> ProjectZoneClusterCreateCall<'a, C, NC, A> { + self._zone_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterCreateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterCreateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneClusterCreateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/content2/Cargo.toml b/gen/content2/Cargo.toml new file mode 100644 index 0000000000..52bb7e8fd7 --- /dev/null +++ b/gen/content2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-content2" +version = "0.1.0+20150311" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Shopping Content (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/content2" +homepage = "https://developers.google.com/shopping-content/v2/" +documentation = "http://byron.github.io/google-apis-rs/google-content2" +license = "MIT" +keywords = ["content", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/content2/LICENSE.md b/gen/content2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/content2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/content2/README.md b/gen/content2/README.md new file mode 100644 index 0000000000..39a2c1e480 --- /dev/null +++ b/gen/content2/README.md @@ -0,0 +1,192 @@ + +The `google-content2` library allows access to all features of the *Google Shopping Content* service. + +This documentation was generated from *Shopping Content* crate version *0.1.0+20150311*, where *20150311* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *Shopping Content* *v2* API can be found at the +[official documentation site](https://developers.google.com/shopping-content/v2/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-content2/struct.ShoppingContent.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google-content2/struct.Account.html) + * [*authinfo*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountAuthinfoCall.html), [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountCustombatchCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountUpdateCall.html) +* accountshipping + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountshippingCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountshippingGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountshippingListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountshippingPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountshippingUpdateCall.html) +* accountstatuses + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountstatuseCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountstatuseGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.AccountstatuseListCall.html) +* accounttax + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccounttaxCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.AccounttaxGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.AccounttaxListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-content2/struct.AccounttaxPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-content2/struct.AccounttaxUpdateCall.html) +* [datafeeds](http://byron.github.io/google-apis-rs/google-content2/struct.Datafeed.html) + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedCustombatchCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedUpdateCall.html) +* datafeedstatuses + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedstatuseCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedstatuseGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.DatafeedstatuseListCall.html) +* [inventory](http://byron.github.io/google-apis-rs/google-content2/struct.Inventory.html) + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.InventoryCustombatchCall.html) and [*set*](http://byron.github.io/google-apis-rs/google-content2/struct.InventorySetCall.html) +* [products](http://byron.github.io/google-apis-rs/google-content2/struct.Product.html) + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductCustombatchCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductListCall.html) +* productstatuses + * [*custombatch*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductstatuseCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductstatuseGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-content2/struct.ProductstatuseListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-content2/struct.ShoppingContent.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-content2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-content2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-content2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.accounts().custombatch(...).doit() +let r = hub.accounts().patch(...).doit() +let r = hub.accounts().get(...).doit() +let r = hub.accounts().update(...).doit() +let r = hub.accounts().list(...).doit() +let r = hub.accounts().authinfo(...).doit() +let r = hub.accounts().delete(...).doit() +let r = hub.accounts().insert(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-content2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-content2" as content2; +use content2::Account; +use content2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use content2::ShoppingContent; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Account = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.accounts().patch(&req, "merchantId", "accountId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-content2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-content2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-content2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-content2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-content2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-content2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-content2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-content2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-content2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-content2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-content2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-content2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-content2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **content2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/content2/src/cmn.rs b/gen/content2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/content2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/content2/src/lib.rs b/gen/content2/src/lib.rs new file mode 100644 index 0000000000..f8adf6fdc7 --- /dev/null +++ b/gen/content2/src/lib.rs @@ -0,0 +1,13644 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Shopping Content* crate version *0.1.0+20150311*, where *20150311* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *Shopping Content* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/shopping-content/v2/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/content2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.ShoppingContent.html) ... +//! +//! * [accounts](struct.Account.html) +//! * [*authinfo*](struct.AccountAuthinfoCall.html), [*custombatch*](struct.AccountCustombatchCall.html), [*delete*](struct.AccountDeleteCall.html), [*get*](struct.AccountGetCall.html), [*insert*](struct.AccountInsertCall.html), [*list*](struct.AccountListCall.html), [*patch*](struct.AccountPatchCall.html) and [*update*](struct.AccountUpdateCall.html) +//! * accountshipping +//! * [*custombatch*](struct.AccountshippingCustombatchCall.html), [*get*](struct.AccountshippingGetCall.html), [*list*](struct.AccountshippingListCall.html), [*patch*](struct.AccountshippingPatchCall.html) and [*update*](struct.AccountshippingUpdateCall.html) +//! * accountstatuses +//! * [*custombatch*](struct.AccountstatuseCustombatchCall.html), [*get*](struct.AccountstatuseGetCall.html) and [*list*](struct.AccountstatuseListCall.html) +//! * accounttax +//! * [*custombatch*](struct.AccounttaxCustombatchCall.html), [*get*](struct.AccounttaxGetCall.html), [*list*](struct.AccounttaxListCall.html), [*patch*](struct.AccounttaxPatchCall.html) and [*update*](struct.AccounttaxUpdateCall.html) +//! * [datafeeds](struct.Datafeed.html) +//! * [*custombatch*](struct.DatafeedCustombatchCall.html), [*delete*](struct.DatafeedDeleteCall.html), [*get*](struct.DatafeedGetCall.html), [*insert*](struct.DatafeedInsertCall.html), [*list*](struct.DatafeedListCall.html), [*patch*](struct.DatafeedPatchCall.html) and [*update*](struct.DatafeedUpdateCall.html) +//! * datafeedstatuses +//! * [*custombatch*](struct.DatafeedstatuseCustombatchCall.html), [*get*](struct.DatafeedstatuseGetCall.html) and [*list*](struct.DatafeedstatuseListCall.html) +//! * [inventory](struct.Inventory.html) +//! * [*custombatch*](struct.InventoryCustombatchCall.html) and [*set*](struct.InventorySetCall.html) +//! * [products](struct.Product.html) +//! * [*custombatch*](struct.ProductCustombatchCall.html), [*delete*](struct.ProductDeleteCall.html), [*get*](struct.ProductGetCall.html), [*insert*](struct.ProductInsertCall.html) and [*list*](struct.ProductListCall.html) +//! * productstatuses +//! * [*custombatch*](struct.ProductstatuseCustombatchCall.html), [*get*](struct.ProductstatuseGetCall.html) and [*list*](struct.ProductstatuseListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.ShoppingContent.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.accounts().custombatch(...).doit() +//! let r = hub.accounts().patch(...).doit() +//! let r = hub.accounts().get(...).doit() +//! let r = hub.accounts().update(...).doit() +//! let r = hub.accounts().list(...).doit() +//! let r = hub.accounts().authinfo(...).doit() +//! let r = hub.accounts().delete(...).doit() +//! let r = hub.accounts().insert(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-content2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-content2" as content2; +//! use content2::Account; +//! use content2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use content2::ShoppingContent; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Account = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.accounts().patch(&req, "merchantId", "accountId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your product listings and accounts for Google Shopping + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/content", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all ShoppingContent related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// use content2::Account; +/// use content2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().patch(&req, "merchantId", "accountId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct ShoppingContent { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for ShoppingContent {} + +impl<'a, C, NC, A> ShoppingContent + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> ShoppingContent { + ShoppingContent { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + pub fn accountshipping(&'a self) -> AccountshippingMethods<'a, C, NC, A> { + AccountshippingMethods { hub: &self } + } + pub fn accountstatuses(&'a self) -> AccountstatuseMethods<'a, C, NC, A> { + AccountstatuseMethods { hub: &self } + } + pub fn accounttax(&'a self) -> AccounttaxMethods<'a, C, NC, A> { + AccounttaxMethods { hub: &self } + } + pub fn datafeeds(&'a self) -> DatafeedMethods<'a, C, NC, A> { + DatafeedMethods { hub: &self } + } + pub fn datafeedstatuses(&'a self) -> DatafeedstatuseMethods<'a, C, NC, A> { + DatafeedstatuseMethods { hub: &self } + } + pub fn inventory(&'a self) -> InventoryMethods<'a, C, NC, A> { + InventoryMethods { hub: &self } + } + pub fn products(&'a self) -> ProductMethods<'a, C, NC, A> { + ProductMethods { hub: &self } + } + pub fn productstatuses(&'a self) -> ProductstatuseMethods<'a, C, NC, A> { + ProductstatuseMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A list of errors returned by a failed batch entry. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Errors { + /// The message of the first error in errors. + pub message: String, + /// The HTTP status of the first error in errors. + pub code: u32, + /// A list of errors. + pub errors: Vec, +} + +impl Part for Errors {} + + +/// A batch entry encoding a single non-batch products response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductsCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// Identifies what kind of resource this is. Value: the fixed string "content#productsCustomBatchResponseEntry". + pub kind: String, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// The inserted product. Only defined if the method is insert and if the request was successful. + pub product: Product, +} + +impl Part for ProductsCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accounttax](struct.AccounttaxCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccounttaxCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for AccounttaxCustomBatchResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accountshipping](struct.AccountshippingCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountshippingCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for AccountshippingCustomBatchResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch inventory](struct.InventoryCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InventoryCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for InventoryCustomBatchResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountUser { + /// Whether user is an admin. + pub admin: bool, + /// User's email address. + #[serde(alias="emailAddress")] + pub email_address: String, +} + +impl Part for AccountUser {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingRateTableCell { + /// The rate applicable if the cell conditions are matched. + pub rate: Price, + /// Conditions for which the cell is valid. All cells in a table must use the same dimension or pair of dimensions among price, weight, shipping label or delivery location. If no condition is specified, the cell acts as a catch-all and matches all the elements that are not matched by other cells in this dimension. + pub condition: AccountShippingCondition, +} + +impl Part for AccountShippingRateTableCell {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch productstatuses](struct.ProductstatuseCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ProductstatusesCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for ProductstatusesCustomBatchRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch datafeeds](struct.DatafeedCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedsCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for DatafeedsCustomBatchResponse {} + + +/// A user-defined locations group in a given country. All the locations of the group must be of the same type. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingLocationGroup { + /// A postal code range representing a city or a set of cities. + #[serde(alias="postalCodeRanges")] + pub postal_code_ranges: Vec, + /// The country in which this location group is, represented as ISO 3166-1 Alpha-2 code. + pub country: String, + /// A location ID (also called criteria ID) representing administrative areas, smaller country subdivisions (counties), or cities. + #[serde(alias="locationIds")] + pub location_ids: Vec, + /// The name of the location group. + pub name: String, + /// A postal code representing a city or a set of cities. + /// - A single postal code (e.g., 12345) + /// - A postal code prefix followed by a star (e.g., 1234*) + #[serde(alias="postalCodes")] + pub postal_codes: Vec, +} + +impl Part for AccountShippingLocationGroup {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set inventory](struct.InventorySetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InventorySetResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#inventorySetResponse". + pub kind: String, +} + +impl ResponseResult for InventorySetResponse {} + + +/// The status of a product, i.e., information about a product computed asynchronously by the data quality analysis. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get productstatuses](struct.ProductstatuseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductStatus { + /// Date on which the item expires in Google Shopping, in ISO 8601 format. + #[serde(alias="googleExpirationDate")] + pub google_expiration_date: String, + /// The intended destinations for the product. + #[serde(alias="destinationStatuses")] + pub destination_statuses: Vec, + /// The title of the product. + pub title: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#productStatus". + pub kind: String, + /// Date on which the item has been last updated, in ISO 8601 format. + #[serde(alias="lastUpdateDate")] + pub last_update_date: String, + /// The link to the product. + pub link: String, + /// Date on which the item has been created, in ISO 8601 format. + #[serde(alias="creationDate")] + pub creation_date: String, + /// A list of data quality issues associated with the product. + #[serde(alias="dataQualityIssues")] + pub data_quality_issues: Vec, + /// The id of the product for which status is reported. + #[serde(alias="productId")] + pub product_id: String, +} + +impl ResponseResult for ProductStatus {} + + +/// The required fields vary based on the frequency of fetching. For a monthly fetch schedule, day_of_month and hour are required. For a weekly fetch schedule, weekday and hour are required. For a daily fetch schedule, only hour is required. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatafeedFetchSchedule { + /// An optional user name for fetch_url. + pub username: String, + /// An optional password for fetch_url. + pub password: String, + /// The day of the week the feed file should be fetched. + pub weekday: String, + /// The hour of the day the feed file should be fetched (0-24). + pub hour: u32, + /// Time zone used for schedule. UTC by default. E.g., "America/Los_Angeles". + #[serde(alias="timeZone")] + pub time_zone: String, + /// The URL where the feed file can be fetched. Google Merchant Center will support automatic scheduled uploads using the HTTP, HTTPS, FTP, or SFTP protocols, so the value will need to be a valid link using one of those four protocols. + #[serde(alias="fetchUrl")] + pub fetch_url: String, + /// The day of the month the feed file should be fetched (1-31). + #[serde(alias="dayOfMonth")] + pub day_of_month: u32, +} + +impl Part for DatafeedFetchSchedule {} + + +/// The status of a datafeed, i.e., the result of the last retrieval of the datafeed computed asynchronously when the feed processing is finished. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get datafeedstatuses](struct.DatafeedstatuseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedStatus { + /// The number of items in the feed that were valid. + #[serde(alias="itemsValid")] + pub items_valid: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedStatus". + pub kind: String, + /// The list of errors occurring in the feed. + pub errors: Vec, + /// The processing status of the feed. + #[serde(alias="processingStatus")] + pub processing_status: String, + /// The number of items in the feed that were processed. + #[serde(alias="itemsTotal")] + pub items_total: String, + /// The ID of the feed for which the status is reported. + #[serde(alias="datafeedId")] + pub datafeed_id: String, + /// The list of errors occurring in the feed. + pub warnings: Vec, +} + +impl ResponseResult for DatafeedStatus {} + + +/// A batch entry encoding a single non-batch datafeedstatuses request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DatafeedstatusesCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The ID of the data feed to get or delete. + #[serde(alias="datafeedId")] + pub datafeed_id: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, +} + +impl Part for DatafeedstatusesCustomBatchRequestEntry {} + + +/// A batch entry encoding a single non-batch accounttax response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccounttaxCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The retrieved or updated account tax settings. + #[serde(alias="accountTax")] + pub account_tax: AccountTax, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponseEntry". + pub kind: String, +} + +impl Part for AccounttaxCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accountstatuses](struct.AccountstatuseCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountstatusesCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for AccountstatusesCustomBatchRequest {} + + +/// Building block of the cost calculation decision tree. +/// - The tree root should have no condition and no calculation method. +/// - All the children must have a condition on the same dimension. The first child matching a condition is entered, therefore, price and weight conditions form contiguous intervals. +/// - The last child of an element must have no condition and matches all elements not previously matched. +/// - Children and calculation method are mutually exclusive, and exactly one of them must be defined; the root must only have children. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingShippingServiceCostRule { + /// Final calculation method to be used only in leaf nodes. + #[serde(alias="calculationMethod")] + pub calculation_method: AccountShippingShippingServiceCalculationMethod, + /// Condition for this rule to be applicable. If no condition is specified, the rule acts as a catch-all. + pub condition: AccountShippingCondition, + /// Subsequent rules to be applied, only for inner nodes. The last child must not specify a condition and acts as a catch-all. + pub children: Vec, +} + +impl Part for AccountShippingShippingServiceCostRule {} + + +/// Account data. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accounts](struct.AccountCustombatchCall.html) (none) +/// * [patch accounts](struct.AccountPatchCall.html) (request|response) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// * [update accounts](struct.AccountUpdateCall.html) (request|response) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [authinfo accounts](struct.AccountAuthinfoCall.html) (none) +/// * [delete accounts](struct.AccountDeleteCall.html) (none) +/// * [insert accounts](struct.AccountInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Account { + /// URL for individual seller reviews, i.e., reviews for each child account. + #[serde(alias="reviewsUrl")] + pub reviews_url: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#account". + pub kind: Option, + /// Display name for the account. + pub name: Option, + /// Indicates whether the merchant sells adult content. + #[serde(alias="adultContent")] + pub adult_content: Option, + /// List of linked AdWords accounts. + #[serde(alias="adwordsLinks")] + pub adwords_links: Option>, + /// The merchant's website. + #[serde(alias="websiteUrl")] + pub website_url: Option, + /// Client-specific, locally-unique, internal ID for the child account. + #[serde(alias="sellerId")] + pub seller_id: Option, + /// Merchant Center account ID. + pub id: Option, + /// Users with access to the account. Every account (except for subaccounts) must have at least one admin user. + pub users: Option>, +} + +impl RequestValue for Account {} +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// Account identifier corresponding to the authenticated user. +/// - For an individual account: only the merchant ID is defined +/// - For an aggregator: only the aggregator ID is defined +/// - For a subaccount of an MCA: both the merchant ID and the aggregator ID are defined. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountIdentifier { + /// The aggregator ID, set for aggregators and subaccounts (in that case, it represents the aggregator of the subaccount). + #[serde(alias="aggregatorId")] + pub aggregator_id: String, + /// The merchant account ID, set for individual accounts and subaccounts. + #[serde(alias="merchantId")] + pub merchant_id: String, +} + +impl Part for AccountIdentifier {} + + +/// A batch entry encoding a single non-batch inventory response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct InventoryCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponseEntry". + pub kind: String, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, +} + +impl Part for InventoryCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductCustomGroup { + /// The sub-attributes. + pub attributes: Vec, + /// The name of the group. Underscores will be replaced by spaces upon insertion. + pub name: String, +} + +impl Part for ProductCustomGroup {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductShippingDimension { + /// The unit of value. + /// + /// Acceptable values are: + /// - "cm" + /// - "in" + pub unit: String, + /// The dimension of the product used to calculate the shipping cost of the item. + pub value: f64, +} + +impl Part for ProductShippingDimension {} + + +/// A batch entry encoding a single non-batch accountstatuses response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountstatusesCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// The requested account status. Defined if and only if the request was successful. + #[serde(alias="accountStatus")] + pub account_status: AccountStatus, +} + +impl Part for AccountstatusesCustomBatchResponseEntry {} + + +/// A batch entry encoding a single non-batch accountstatuses request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountstatusesCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The ID of the (sub-)account whose status to get. + #[serde(alias="accountId")] + pub account_id: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// The method (get). + pub method: String, +} + +impl Part for AccountstatusesCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounttax](struct.AccounttaxListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccounttaxListResponse { + /// The token for the retrieval of the next page of account tax settings. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for AccounttaxListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch datafeedstatuses](struct.DatafeedstatuseCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DatafeedstatusesCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for DatafeedstatusesCustomBatchRequest {} + + +/// An error returned by the API. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Error { + /// The error code. + pub reason: String, + /// A description of the error. + pub message: String, + /// The domain of the error. + pub domain: String, +} + +impl Part for Error {} + + +/// A batch entry encoding a single non-batch datafeeds response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedsCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// The requested data feed. Defined if and only if the request was successful. + pub datafeed: Datafeed, +} + +impl Part for DatafeedsCustomBatchResponseEntry {} + + +/// A batch entry encoding a single non-batch accountshipping request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountshippingCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The ID of the account for which to get/update account shipping settings. + #[serde(alias="accountId")] + pub account_id: String, + /// The account shipping settings to update. Only defined if the method is update. + #[serde(alias="accountShipping")] + pub account_shipping: AccountShipping, + /// no description provided + pub method: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, +} + +impl Part for AccountshippingCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list datafeeds](struct.DatafeedListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedsListResponse { + /// The token for the retrieval of the next page of datafeeds. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedsListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for DatafeedsListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductShipping { + /// The numeric id of a location that the shipping rate applies to as defined in the AdWords API. + #[serde(alias="locationId")] + pub location_id: String, + /// A free-form description of the service class or delivery speed. + pub service: String, + /// The postal code range that the shipping rate applies to, represented by a postal code, a postal code prefix followed by a * wildcard, a range between two postal codes or two postal code prefixes of equal length. + #[serde(alias="postalCode")] + pub postal_code: String, + /// The two-letter ISO 3166 country code for the country to which an item will ship. + pub country: String, + /// Fixed shipping price, represented as a number. + pub price: Price, + /// The geographic region to which a shipping rate applies (e.g. zip code). + pub region: String, + /// The location where the shipping is applicable, represented by a location group name. + #[serde(alias="locationGroupName")] + pub location_group_name: String, +} + +impl Part for ProductShipping {} + + +/// The tax settings of a merchant account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update accounttax](struct.AccounttaxUpdateCall.html) (request|response) +/// * [patch accounttax](struct.AccounttaxPatchCall.html) (request|response) +/// * [get accounttax](struct.AccounttaxGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountTax { + /// Tax rules. Updating the tax rules will enable US taxes (not reversible). Defining no rules is equivalent to not charging tax at all. + pub rules: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountTax". + pub kind: Option, + /// The ID of the account to which these account tax settings belong. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for AccountTax {} +impl ResponseResult for AccountTax {} + + +/// A batch entry encoding a single non-batch products request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ProductsCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The product to insert. Only required if the method is insert. + pub product: Product, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, + /// The ID of the product to get or delete. Only defined if the method is get or delete. + #[serde(alias="productId")] + pub product_id: String, +} + +impl Part for ProductsCustomBatchRequestEntry {} + + +/// A batch entry encoding a single non-batch accounts response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The retrieved, created, or updated account. Not defined if the method was delete. + pub account: Account, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountsCustomBatchResponseEntry". + pub kind: String, +} + +impl Part for AccountsCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accounts](struct.AccountCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountsCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for AccountsCustomBatchRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch productstatuses](struct.ProductstatuseCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#productstatusesCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for ProductstatusesCustomBatchResponse {} + + +/// A carrier-calculated shipping rate. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingCarrierRate { + /// Shipping origin represented as a postal code. + #[serde(alias="shippingOrigin")] + pub shipping_origin: String, + /// The carrier that is responsible for the shipping, such as "UPS", "FedEx", or "USPS". + pub carrier: String, + /// The name of the carrier rate. + pub name: String, + /// Sale country for which this carrier rate is valid, represented as an ISO 3166-1 Alpha-2 code. + #[serde(alias="saleCountry")] + pub sale_country: i64, + /// The carrier service, such as "Ground" or "2Day". + #[serde(alias="carrierService")] + pub carrier_service: String, + /// Additive shipping rate modifier. + #[serde(alias="modifierFlatRate")] + pub modifier_flat_rate: Price, + /// Multiplicative shipping rate modifier in percent. Represented as a floating point number without the percentage character. + #[serde(alias="modifierPercent")] + pub modifier_percent: String, +} + +impl Part for AccountShippingCarrierRate {} + + +/// Datafeed data. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert datafeeds](struct.DatafeedInsertCall.html) (request|response) +/// * [custombatch datafeeds](struct.DatafeedCustombatchCall.html) (none) +/// * [patch datafeeds](struct.DatafeedPatchCall.html) (request|response) +/// * [list datafeeds](struct.DatafeedListCall.html) (none) +/// * [delete datafeeds](struct.DatafeedDeleteCall.html) (none) +/// * [get datafeeds](struct.DatafeedGetCall.html) (response) +/// * [update datafeeds](struct.DatafeedUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Datafeed { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeed". + pub kind: Option, + /// The type of data feed. + #[serde(alias="contentType")] + pub content_type: Option, + /// A descriptive name of the data feed. + pub name: Option, + /// The two-letter ISO 639-1 language of the items in the feed. + #[serde(alias="contentLanguage")] + pub content_language: Option, + /// Format of the feed file. + pub format: Option, + /// Fetch schedule for the feed file. + #[serde(alias="fetchSchedule")] + pub fetch_schedule: Option, + /// The two-letter ISO 3166 country where the items in the feed will be included in the search index. + #[serde(alias="targetCountry")] + pub target_country: Option, + /// The filename of the feed. All feeds must have a unique file name. + #[serde(alias="fileName")] + pub file_name: Option, + /// The ID of the data feed. + pub id: Option, + /// The list of intended destinations (corresponds to checked check boxes in Merchant Center). + #[serde(alias="intendedDestinations")] + pub intended_destinations: Option>, + /// The two-letter ISO 639-1 language in which the attributes are defined in the data feed. + #[serde(alias="attributeLanguage")] + pub attribute_language: Option, +} + +impl RequestValue for Datafeed {} +impl Resource for Datafeed {} +impl ResponseResult for Datafeed {} + + +/// Shipping cost calculation method. Exactly one of the field is set. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingShippingServiceCalculationMethod { + /// Percentage of the price, represented as a floating point number without the percentage character. + #[serde(alias="percentageRate")] + pub percentage_rate: String, + /// Name of the carrier rate to use for the calculation. + #[serde(alias="carrierRate")] + pub carrier_rate: String, + /// Name of the rate table to use for the calculation. + #[serde(alias="rateTable")] + pub rate_table: String, + /// Delivery is excluded. Valid only within cost rules tree. + pub excluded: bool, + /// Fixed price shipping, represented as a floating point number associated with a currency. + #[serde(alias="flatRate")] + pub flat_rate: Price, +} + +impl Part for AccountShippingShippingServiceCalculationMethod {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductTax { + /// The percentage of tax rate that applies to the item price. + pub rate: f64, + /// The numeric id of a location that the tax rate applies to as defined in the AdWords API. + #[serde(alias="locationId")] + pub location_id: String, + /// The postal code range that the tax rate applies to, represented by a ZIP code, a ZIP code prefix using * wildcard, a range between two ZIP codes or two ZIP code prefixes of equal length. Examples: 94114, 94*, 94002-95460, 94*-95*. + #[serde(alias="postalCode")] + pub postal_code: String, + /// The country within which the item is taxed, specified with a two-letter ISO 3166 country code. + pub country: String, + /// The geographic region to which the tax rate applies. + pub region: String, + /// Set to true if tax is charged on shipping. + #[serde(alias="taxShip")] + pub tax_ship: bool, +} + +impl Part for ProductTax {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch datafeedstatuses](struct.DatafeedstatuseCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for DatafeedstatusesCustomBatchResponse {} + + +/// A batch entry encoding a single non-batch accounts request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountsCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The account to create or update. Only defined if the method is insert or update. + pub account: Account, + /// The ID of the account to get or delete. Only defined if the method is get or delete. + #[serde(alias="accountId")] + pub account_id: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, +} + +impl Part for AccountsCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [authinfo accounts](struct.AccountAuthinfoCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsAuthInfoResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountsAuthInfoResponse". + pub kind: String, + /// The account identifiers corresponding to the authenticated user. + #[serde(alias="accountIdentifiers")] + pub account_identifiers: Vec, +} + +impl ResponseResult for AccountsAuthInfoResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch products](struct.ProductCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ProductsCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for ProductsCustomBatchRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list datafeedstatuses](struct.DatafeedstatuseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedstatusesListResponse { + /// The token for the retrieval of the next page of datafeed statuses. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for DatafeedstatusesListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductUnitPricingMeasure { + /// The unit of the measure. + pub unit: String, + /// The measure of an item. + pub value: f64, +} + +impl Part for ProductUnitPricingMeasure {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accountstatuses](struct.AccountstatuseCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountstatusesCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for AccountstatusesCustomBatchResponse {} + + +/// The status of an account, i.e., information about its products, which is computed offline and not returned immediately at insertion time. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get accountstatuses](struct.AccountstatuseGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountStatus { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountStatus". + pub kind: String, + /// A list of data quality issues. + #[serde(alias="dataQualityIssues")] + pub data_quality_issues: Vec, + /// The ID of the account for which the status is reported. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl ResponseResult for AccountStatus {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductInstallment { + /// The amount the buyer has to pay per month. + pub amount: Price, + /// The number of installments the buyer has to pay. + pub months: String, +} + +impl Part for ProductInstallment {} + + +/// A batch entry encoding a single non-batch datafeedstatuses response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedstatusesCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// The requested data feed status. Defined if and only if the request was successful. + #[serde(alias="datafeedStatus")] + pub datafeed_status: DatafeedStatus, +} + +impl Part for DatafeedstatusesCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct Inventory { + /// Identifies what kind of resource this is. Value: the fixed string "content#inventory". + pub kind: String, + /// The sale price of the product. Mandatory if sale_price_effective_date is defined. + #[serde(alias="salePrice")] + pub sale_price: Price, + /// A date range represented by a pair of ISO 8601 dates separated by a space, comma, or slash. Both dates might be specified as 'null' if undecided. + #[serde(alias="salePriceEffectiveDate")] + pub sale_price_effective_date: String, + /// The price of the product. + pub price: Price, + /// The availability of the product. + pub availability: String, + /// The quantity of the product. Must be equal to or greater than zero. Supported only for local products. + pub quantity: u32, +} + +impl Part for Inventory {} + + +/// A single or bi-dimensional table of shipping rates. Each dimension is defined in terms of consecutive price/weight ranges, delivery locations, or shipping labels. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingRateTable { + /// One-dimensional table cells define one condition along the same dimension. Bi-dimensional table cells use two dimensions with respectively M and N distinct values and must contain exactly M * N cells with distinct conditions (for each possible value pairs). + pub content: Vec, + /// Sale country for which this table is valid, represented as an ISO 3166-1 Alpha-2 code. + #[serde(alias="saleCountry")] + pub sale_country: i64, + /// The name of the rate table. + pub name: String, +} + +impl Part for AccountShippingRateTable {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductStatusDestinationStatus { + /// The destination's approval status. + #[serde(alias="approvalStatus")] + pub approval_status: String, + /// The name of the destination + pub destination: String, + /// Whether the destination is required, excluded, selected by default or should be validated. + pub intention: String, +} + +impl Part for ProductStatusDestinationStatus {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accounttax](struct.AccounttaxCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccounttaxCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for AccounttaxCustomBatchRequest {} + + +/// A batch entry encoding a single non-batch inventory request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InventoryCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The code of the store for which to update price and availability. Use online to update price and availability of an online product. + #[serde(alias="storeCode")] + pub store_code: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// Price and availability of the product. + pub inventory: Inventory, + /// The ID of the product for which to update price and availability. + #[serde(alias="productId")] + pub product_id: String, +} + +impl Part for InventoryCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch products](struct.ProductCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#productsCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for ProductsCustomBatchResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accountshipping](struct.AccountshippingListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountshippingListResponse { + /// The token for the retrieval of the next page of account shipping settings. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for AccountshippingListResponse {} + + +/// An example of an item that has poor data quality. An item value on the landing page differs from what is submitted, or conflicts with a policy. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountStatusExampleItem { + /// Unique item ID as specified in the uploaded product data. + #[serde(alias="itemId")] + pub item_id: String, + /// The item value that was submitted. + #[serde(alias="submittedValue")] + pub submitted_value: String, + /// Landing page of the item. + pub link: String, + /// The actual value on the landing page. + #[serde(alias="valueOnLandingPage")] + pub value_on_landing_page: String, + /// Title of the item. + pub title: String, +} + +impl Part for AccountStatusExampleItem {} + + +/// A batch entry encoding a single non-batch productstatuses request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ProductstatusesCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, + /// The ID of the product whose status to get. + #[serde(alias="productId")] + pub product_id: String, +} + +impl Part for ProductstatusesCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Price { + /// The currency of the price. + pub currency: String, + /// The price represented as a number. + pub value: String, +} + +impl Part for Price {} + + +/// An error occurring in the feed, like "invalid price". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedStatusError { + /// The number of occurrences of the error in the feed. + pub count: String, + /// The error message, e.g., "Invalid price". + pub message: String, + /// The code of the error, e.g., "validation/invalid_value". + pub code: String, + /// A list of example occurrences of the error, grouped by product. + pub examples: Vec, +} + +impl Part for DatafeedStatusError {} + + +/// An example occurrence for a particular error. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DatafeedStatusExample { + /// The ID of the example item. + #[serde(alias="itemId")] + pub item_id: String, + /// The problematic value. + pub value: String, + /// Line number in the data feed where the example is found. + #[serde(alias="lineNumber")] + pub line_number: String, +} + +impl Part for DatafeedStatusExample {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductShippingWeight { + /// The unit of value. + pub unit: String, + /// The weight of the product used to calculate the shipping cost of the item. + pub value: f64, +} + +impl Part for ProductShippingWeight {} + + +/// A batch entry encoding a single non-batch accounttax request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccounttaxCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The account tax settings to update. Only defined if the method is update. + #[serde(alias="accountTax")] + pub account_tax: AccountTax, + /// The ID of the account for which to get/update account tax settings. + #[serde(alias="accountId")] + pub account_id: String, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, +} + +impl Part for AccounttaxCustomBatchRequestEntry {} + + +/// The shipping settings of a merchant account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update accountshipping](struct.AccountshippingUpdateCall.html) (request|response) +/// * [patch accountshipping](struct.AccountshippingPatchCall.html) (request|response) +/// * [get accountshipping](struct.AccountshippingGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShipping { + /// Carrier-based shipping calculations. + #[serde(alias="carrierRates")] + pub carrier_rates: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountShipping". + pub kind: Option, + /// Location groups for shipping. + #[serde(alias="locationGroups")] + pub location_groups: Option>, + /// Shipping services describing shipping fees calculation. + pub services: Option>, + /// The ID of the account to which these account shipping settings belong. + #[serde(alias="accountId")] + pub account_id: Option, + /// Rate tables definitions. + #[serde(alias="rateTables")] + pub rate_tables: Option>, +} + +impl RequestValue for AccountShipping {} +impl ResponseResult for AccountShipping {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductUnitPricingBaseMeasure { + /// The unit of the denominator. + pub unit: String, + /// The denominator of the unit price. + pub value: String, +} + +impl Part for ProductUnitPricingBaseMeasure {} + + +/// Tax calculation rule to apply in a state or province (USA only). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountTaxTaxRule { + /// Country code in which tax is applicable. + pub country: String, + /// Explicit tax rate in percent, represented as a floating point number without the percentage character. Must not be negative. + #[serde(alias="ratePercent")] + pub rate_percent: String, + /// If true, shipping charges are also taxed. + #[serde(alias="shippingTaxed")] + pub shipping_taxed: bool, + /// State (or province) is which the tax is applicable, described by its location id (also called criteria id). + #[serde(alias="locationId")] + pub location_id: String, + /// Whether the tax rate is taken from a global tax table or specified explicitly. + #[serde(alias="useGlobalRate")] + pub use_global_rate: bool, +} + +impl Part for AccountTaxTaxRule {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductCustomAttribute { + /// Free-form unit of the attribute. Unit can only be used for values of type INT or FLOAT. + pub unit: String, + /// The type of the attribute. + #[serde(alias="type")] + pub type_: String, + /// The name of the attribute. Underscores will be replaced by spaces upon insertion. + pub name: String, + /// The value of the attribute. + pub value: String, +} + +impl Part for ProductCustomAttribute {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accountstatuses](struct.AccountstatuseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountstatusesListResponse { + /// The token for the retrieval of the next page of account statuses. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountstatusesListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for AccountstatusesListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingCondition { + /// Maximum shipping weight. Forms an interval between the maximum of smaller weight (exclusive) and this weight (inclusive). + #[serde(alias="weightMax")] + pub weight_max: Weight, + /// Delivery location in terms of a location ID. Can be used to represent administrative areas, smaller country subdivisions, or cities. + #[serde(alias="deliveryLocationId")] + pub delivery_location_id: String, + /// Shipping label of the product. The products with the label are matched. + #[serde(alias="shippingLabel")] + pub shipping_label: String, + /// Delivery location in terms of a location group name. A location group with this name must be specified among location groups. + #[serde(alias="deliveryLocationGroup")] + pub delivery_location_group: String, + /// Delivery location in terms of a postal code. + #[serde(alias="deliveryPostalCode")] + pub delivery_postal_code: String, + /// Maximum shipping price. Forms an interval between the maximum of smaller prices (exclusive) and this price (inclusive). + #[serde(alias="priceMax")] + pub price_max: Price, + /// Delivery location in terms of a postal code range. + #[serde(alias="deliveryPostalCodeRange")] + pub delivery_postal_code_range: AccountShippingPostalCodeRange, +} + +impl Part for AccountShippingCondition {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch inventory](struct.InventoryCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InventoryCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for InventoryCustomBatchRequest {} + + +/// Product data. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete products](struct.ProductDeleteCall.html) (none) +/// * [custombatch products](struct.ProductCustombatchCall.html) (none) +/// * [get products](struct.ProductGetCall.html) (response) +/// * [list products](struct.ProductListCall.html) (none) +/// * [insert products](struct.ProductInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Product { + /// Set to true if the item is targeted towards adults. + pub adult: Option, + /// Color of the item. + pub color: Option, + /// Similar to adwords_grouping, but only works on CPC. + #[serde(alias="adwordsLabels")] + pub adwords_labels: Option>, + /// Shared identifier for all variants of the same product. + #[serde(alias="itemGroupId")] + pub item_group_id: Option, + /// Date on which the item should expire, as specified upon insertion, in ISO 8601 format. The actual expiration date in Google Shopping is exposed in productstatuses as googleExpirationDate and might be earlier if expirationDate is too far in the future. + #[serde(alias="expirationDate")] + pub expiration_date: Option, + /// Availability status of the item. + pub availability: Option, + /// Used to group items in an arbitrary way. Only for CPA%, discouraged otherwise. + #[serde(alias="adwordsGrouping")] + pub adwords_grouping: Option, + /// Specifies the intended destinations for the product. + pub destinations: Option>, + /// The two-letter ISO 3166 country code for the item. + #[serde(alias="targetCountry")] + pub target_country: Option, + /// Custom label 4 for custom grouping of items in a Shopping campaign. + #[serde(alias="customLabel4")] + pub custom_label4: Option, + /// Title of the item. + pub title: Option, + /// Whether an item is available for purchase only online. + #[serde(alias="onlineOnly")] + pub online_only: Option, + /// Link to a mobile-optimized version of the landing page. + #[serde(alias="mobileLink")] + pub mobile_link: Option, + /// Height of the item for shipping. + #[serde(alias="shippingHeight")] + pub shipping_height: Option, + /// The two-letter ISO 639-1 language code for the item. + #[serde(alias="contentLanguage")] + pub content_language: Option, + /// Manufacturer Part Number (MPN) of the item. + pub mpn: Option, + /// Date range during which the item is on sale (see product feed specifications). + #[serde(alias="salePriceEffectiveDate")] + pub sale_price_effective_date: Option, + /// Brand of the item. + pub brand: Option, + /// The material of which the item is made. + pub material: Option, + /// URL directly linking to your item's page on your website. + pub link: Option, + /// Allows advertisers to override the item URL when the product is shown within the context of Product Ads. + #[serde(alias="adwordsRedirect")] + pub adwords_redirect: Option, + /// The energy efficiency class as defined in EU directive 2010/30/EU. + #[serde(alias="energyEfficiencyClass")] + pub energy_efficiency_class: Option, + /// System in which the size is specified. Recommended for apparel items. + #[serde(alias="sizeSystem")] + pub size_system: Option, + /// The cut of the item. Recommended for apparel items. + #[serde(alias="sizeType")] + pub size_type: Option, + /// Custom label 3 for custom grouping of items in a Shopping campaign. + #[serde(alias="customLabel3")] + pub custom_label3: Option, + /// Custom label 2 for custom grouping of items in a Shopping campaign. + #[serde(alias="customLabel2")] + pub custom_label2: Option, + /// Condition or state of the item. + pub condition: Option, + /// Custom label 0 for custom grouping of items in a Shopping campaign. + #[serde(alias="customLabel0")] + pub custom_label0: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#product". + pub kind: Option, + /// Number and amount of installments to pay for an item. Brazil only. + pub installment: Option, + /// Size of the item. + pub sizes: Option>, + /// Target gender of the item. + pub gender: Option, + /// Tax information. + pub taxes: Option>, + /// False when the item does not have unique product identifiers appropriate to its category, such as GTIN, MPN, and brand. Required according to the Unique Product Identifier Rules for all target countries except for Canada. + #[serde(alias="identifierExists")] + pub identifier_exists: Option, + /// Advertised sale price of the item. + #[serde(alias="salePrice")] + pub sale_price: Option, + /// Your category of the item (formatted as in product feeds specification). + #[serde(alias="productType")] + pub product_type: Option, + /// Advertiser-specified recommendations. + #[serde(alias="displayAdsSimilarIds")] + pub display_ads_similar_ids: Option>, + /// Custom label 1 for custom grouping of items in a Shopping campaign. + #[serde(alias="customLabel1")] + pub custom_label1: Option, + /// Target age group of the item. + #[serde(alias="ageGroup")] + pub age_group: Option, + /// Additional URLs of images of the item. + #[serde(alias="additionalImageLinks")] + pub additional_image_links: Option>, + /// An identifier of the item. + #[serde(alias="offerId")] + pub offer_id: Option, + /// Global Trade Item Number (GTIN) of the item. + pub gtin: Option, + /// The shipping label of the product, used to group product in account-level shipping rules. + #[serde(alias="shippingLabel")] + pub shipping_label: Option, + /// Google's category of the item (see Google product taxonomy). + #[serde(alias="googleProductCategory")] + pub google_product_category: Option, + /// The number of identical products in a merchant-defined multipack. + pub multipack: Option, + /// An identifier for an item for dynamic remarketing campaigns. + #[serde(alias="displayAdsId")] + pub display_ads_id: Option, + /// Offer margin for dynamic remarketing campaigns. + #[serde(alias="displayAdsValue")] + pub display_ads_value: Option, + /// The REST id of the product. + pub id: Option, + /// Width of the item for shipping. + #[serde(alias="shippingWidth")] + pub shipping_width: Option, + /// The item's pattern (e.g. polka dots). + pub pattern: Option, + /// The measure and dimension of an item. + #[serde(alias="unitPricingMeasure")] + pub unit_pricing_measure: Option, + /// A list of custom (merchant-provided) attributes. It can also be used for submitting any attribute of the feed specification in its generic form (e.g., { "name": "size type", "type": "text", "value": "regular" }). This is useful for submitting attributes not explicitly exposed by the API. + #[serde(alias="customAttributes")] + pub custom_attributes: Option>, + /// The day a pre-ordered product becomes available for delivery, in ISO 8601 format. + #[serde(alias="availabilityDate")] + pub availability_date: Option, + /// Whether the item is a merchant-defined bundle. A bundle is a custom grouping of different products sold by a merchant for a single price. + #[serde(alias="isBundle")] + pub is_bundle: Option, + /// The item's channel (online or local). + pub channel: Option, + /// Description of the item. + pub description: Option, + /// Read-only warnings. + pub warnings: Option>, + /// Price of the item. + pub price: Option, + /// Length of the item for shipping. + #[serde(alias="shippingLength")] + pub shipping_length: Option, + /// URL directly to your item's landing page for dynamic remarketing campaigns. + #[serde(alias="displayAdsLink")] + pub display_ads_link: Option, + /// The read-only list of intended destinations which passed validation. + #[serde(alias="validatedDestinations")] + pub validated_destinations: Option>, + /// A list of custom (merchant-provided) custom attribute groups. + #[serde(alias="customGroups")] + pub custom_groups: Option>, + /// Loyalty points that users receive after purchasing the item. Japan only. + #[serde(alias="loyaltyPoints")] + pub loyalty_points: Option, + /// The preference of the denominator of the unit price. + #[serde(alias="unitPricingBaseMeasure")] + pub unit_pricing_base_measure: Option, + /// Shipping rules. + pub shipping: Option>, + /// Weight of the item for shipping. + #[serde(alias="shippingWeight")] + pub shipping_weight: Option, + /// URL of an image of the item. + #[serde(alias="imageLink")] + pub image_link: Option, + /// Title of an item for dynamic remarketing campaigns. + #[serde(alias="displayAdsTitle")] + pub display_ads_title: Option, +} + +impl RequestValue for Product {} +impl Resource for Product {} +impl ResponseResult for Product {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductStatusDataQualityIssue { + /// The value the attribute had at time of evaluation. + #[serde(alias="valueProvided")] + pub value_provided: String, + /// The severity of the data quality issue. + pub severity: String, + /// The time stamp of the data quality issue. + pub timestamp: String, + /// A more detailed error string. + pub detail: String, + /// The attribute name that is relevant for the issue. + pub location: String, + /// The value of that attribute that was found on the landing page + #[serde(alias="valueOnLandingPage")] + pub value_on_landing_page: String, + /// The id of the data quality issue. + pub id: String, + /// The fetch status for landing_page_errors. + #[serde(alias="fetchStatus")] + pub fetch_status: String, +} + +impl Part for ProductStatusDataQualityIssue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list products](struct.ProductListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductsListResponse { + /// The token for the retrieval of the next page of products. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#productsListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for ProductsListResponse {} + + +/// Shipping services provided in a country. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingShippingService { + /// Whether the shipping service is available. + pub active: bool, + /// Decision tree for "complicated" shipping cost calculation. + #[serde(alias="costRuleTree")] + pub cost_rule_tree: AccountShippingShippingServiceCostRule, + /// Sale country for which this service can be used, represented as an ISO 3166-1 Alpha-2 code. + #[serde(alias="saleCountry")] + pub sale_country: i64, + /// Calculation method for the "simple" case that needs no rules. + #[serde(alias="calculationMethod")] + pub calculation_method: AccountShippingShippingServiceCalculationMethod, + /// The name of this shipping service. + pub name: String, +} + +impl Part for AccountShippingShippingService {} + + +/// A batch entry encoding a single non-batch accountshipping response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountshippingCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponseEntry". + pub kind: String, + /// A list of errors defined if and only if the request failed. + pub errors: Errors, + /// The retrieved or updated account shipping settings. + #[serde(alias="accountShipping")] + pub account_shipping: AccountShipping, +} + +impl Part for AccountshippingCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [set inventory](struct.InventorySetCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct InventorySetRequest { + /// A date range represented by a pair of ISO 8601 dates separated by a space, comma, or slash. Both dates might be specified as 'null' if undecided. + #[serde(alias="salePriceEffectiveDate")] + pub sale_price_effective_date: Option, + /// The price of the product. + pub price: Option, + /// The quantity of the product. Must be equal to or greater than zero. Supported only for local products. + pub quantity: Option, + /// The availability of the product. + pub availability: Option, + /// The sale price of the product. Mandatory if sale_price_effective_date is defined. + #[serde(alias="salePrice")] + pub sale_price: Option, +} + +impl RequestValue for InventorySetRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductDestination { + /// Whether the destination is required, excluded or should be validated. + pub intention: String, + /// The name of the destination. + #[serde(alias="destinationName")] + pub destination_name: String, +} + +impl Part for ProductDestination {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accounts](struct.AccountCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountsCustomBatchResponse". + pub kind: String, + /// The result of the execution of the batch requests. + pub entries: Vec, +} + +impl ResponseResult for AccountsCustomBatchResponse {} + + +/// A batch entry encoding a single non-batch datafeeds request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DatafeedsCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(alias="batchId")] + pub batch_id: u32, + /// The ID of the data feed to get or delete. + #[serde(alias="datafeedId")] + pub datafeed_id: String, + /// The data feed to insert. + pub datafeed: Datafeed, + /// The ID of the managing account. + #[serde(alias="merchantId")] + pub merchant_id: String, + /// no description provided + pub method: String, +} + +impl Part for DatafeedsCustomBatchRequestEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list productstatuses](struct.ProductstatuseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductstatusesListResponse { + /// The token for the retrieval of the next page of products statuses. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#productstatusesListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for ProductstatusesListResponse {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Weight { + /// The weight unit. + pub unit: String, + /// The weight represented as a number. + pub value: String, +} + +impl Part for Weight {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountStatusDataQualityIssue { + /// Actual value displayed on the landing page. + #[serde(alias="displayedValue")] + pub displayed_value: String, + /// Severity of the problem. + pub severity: String, + /// Last time the account was checked for this issue. + #[serde(alias="lastChecked")] + pub last_checked: String, + /// Country for which this issue is reported. + pub country: String, + /// Example items featuring the issue. + #[serde(alias="exampleItems")] + pub example_items: Vec, + /// Submitted value that causes the issue. + #[serde(alias="submittedValue")] + pub submitted_value: String, + /// Number of items in the account found to have the said issue. + #[serde(alias="numItems")] + pub num_items: u32, + /// Issue identifier. + pub id: String, +} + +impl Part for AccountStatusDataQualityIssue {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsListResponse { + /// The token for the retrieval of the next page of accounts. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountsListResponse". + pub kind: String, + /// no description provided + pub resources: Vec, +} + +impl ResponseResult for AccountsListResponse {} + + +/// A batch entry encoding a single non-batch productstatuses response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ProductstatusesCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(alias="batchId")] + pub batch_id: u32, + /// Identifies what kind of resource this is. Value: the fixed string "content#productstatusesCustomBatchResponseEntry". + pub kind: String, + /// A list of errors, if the request failed. + pub errors: Errors, + /// The requested product status. Only defined if the request was successful. + #[serde(alias="productStatus")] + pub product_status: ProductStatus, +} + +impl Part for ProductstatusesCustomBatchResponseEntry {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch accountshipping](struct.AccountshippingCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AccountshippingCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for AccountshippingCustomBatchRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LoyaltyPoints { + /// The ratio of a point when converted to currency. Google assumes currency based on Merchant Center settings. If ratio is left out, it defaults to 1.0. + pub ratio: f64, + /// Name of loyalty points program. It is recommended to limit the name to 12 full-width characters or 24 Roman characters. + pub name: String, + /// The retailer's loyalty points in absolute value. + #[serde(alias="pointsValue")] + pub points_value: String, +} + +impl Part for LoyaltyPoints {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [custombatch datafeeds](struct.DatafeedCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DatafeedsCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for DatafeedsCustomBatchRequest {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatafeedFormat { + /// Character encoding scheme of the data feed. If not specified, the encoding will be auto-detected. + #[serde(alias="fileEncoding")] + pub file_encoding: String, + /// Specifies how double quotes are interpreted. If not specified, the mode will be auto-detected. Ignored for non-DSV data feeds. + #[serde(alias="quotingMode")] + pub quoting_mode: String, + /// Delimiter for the separation of values in a delimiter-separated values feed. If not specified, the delimiter will be auto-detected. Ignored for non-DSV data feeds. + #[serde(alias="columnDelimiter")] + pub column_delimiter: String, +} + +impl Part for DatafeedFormat {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountAdwordsLink { + /// Status of the link between this Merchant Center account and the AdWords account. + pub status: String, + /// Customer ID of the AdWords account. + #[serde(alias="adwordsId")] + pub adwords_id: String, +} + +impl Part for AccountAdwordsLink {} + + +/// A postal code range, that can be either: +/// - A range of postal codes (e.g., start=12340, end=12359) +/// - A range of postal codes prefixes (e.g., start=1234* end=1235*). Prefixes must be of the same length (e.g., start=12* end=2* is invalid). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountShippingPostalCodeRange { + /// The first (inclusive) postal code or prefix of the range. + pub start: String, + /// The last (inclusive) postal code or prefix of the range. + pub end: String, +} + +impl Part for AccountShippingPostalCodeRange {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *accounttax* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.accounttax(); +/// # } +/// ``` +pub struct AccounttaxMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccounttaxMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves and updates tax settings of multiple accounts in a single request. + pub fn custombatch(&self, request: &AccounttaxCustomBatchRequest) -> AccounttaxCustombatchCall<'a, C, NC, A> { + AccounttaxCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the tax settings of the account. This method supports patch semantics. + pub fn patch(&self, request: &AccountTax, merchant_id: &str, account_id: &str) -> AccounttaxPatchCall<'a, C, NC, A> { + AccounttaxPatchCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the tax settings of the sub-accounts in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> AccounttaxListCall<'a, C, NC, A> { + AccounttaxListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the tax settings of the account. + pub fn update(&self, request: &AccountTax, merchant_id: &str, account_id: &str) -> AccounttaxUpdateCall<'a, C, NC, A> { + AccounttaxUpdateCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the tax settings of the account. + pub fn get(&self, merchant_id: &str, account_id: &str) -> AccounttaxGetCall<'a, C, NC, A> { + AccounttaxGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *datafeedstatuse* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.datafeedstatuses(); +/// # } +/// ``` +pub struct DatafeedstatuseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DatafeedstatuseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedstatuseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the status of a datafeed from your Merchant Center account. + pub fn get(&self, merchant_id: &str, datafeed_id: &str) -> DatafeedstatuseGetCall<'a, C, NC, A> { + DatafeedstatuseGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _datafeed_id: datafeed_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the statuses of the datafeeds in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> DatafeedstatuseListCall<'a, C, NC, A> { + DatafeedstatuseListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn custombatch(&self, request: &DatafeedstatusesCustomBatchRequest) -> DatafeedstatuseCustombatchCall<'a, C, NC, A> { + DatafeedstatuseCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *datafeed* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.datafeeds(); +/// # } +/// ``` +pub struct DatafeedMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DatafeedMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedMethods<'a, C, NC, A> { + + pub fn custombatch(&self, request: &DatafeedsCustomBatchRequest) -> DatafeedCustombatchCall<'a, C, NC, A> { + DatafeedCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a datafeed from your Merchant Center account. + pub fn get(&self, merchant_id: &str, datafeed_id: &str) -> DatafeedGetCall<'a, C, NC, A> { + DatafeedGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _datafeed_id: datafeed_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a datafeed of your Merchant Center account. This method supports patch semantics. + pub fn patch(&self, request: &Datafeed, merchant_id: &str, datafeed_id: &str) -> DatafeedPatchCall<'a, C, NC, A> { + DatafeedPatchCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _datafeed_id: datafeed_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a datafeed from your Merchant Center account. + pub fn delete(&self, merchant_id: &str, datafeed_id: &str) -> DatafeedDeleteCall<'a, C, NC, A> { + DatafeedDeleteCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _datafeed_id: datafeed_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Registers a datafeed with your Merchant Center account. + pub fn insert(&self, request: &Datafeed, merchant_id: &str) -> DatafeedInsertCall<'a, C, NC, A> { + DatafeedInsertCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the datafeeds in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> DatafeedListCall<'a, C, NC, A> { + DatafeedListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a datafeed of your Merchant Center account. + pub fn update(&self, request: &Datafeed, merchant_id: &str, datafeed_id: &str) -> DatafeedUpdateCall<'a, C, NC, A> { + DatafeedUpdateCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _datafeed_id: datafeed_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *productstatuse* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.productstatuses(); +/// # } +/// ``` +pub struct ProductstatuseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProductstatuseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductstatuseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the status of a product from your Merchant Center account. + pub fn get(&self, merchant_id: &str, product_id: &str) -> ProductstatuseGetCall<'a, C, NC, A> { + ProductstatuseGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _product_id: product_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the statuses of the products in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> ProductstatuseListCall<'a, C, NC, A> { + ProductstatuseListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the statuses of multiple products in a single request. + pub fn custombatch(&self, request: &ProductstatusesCustomBatchRequest) -> ProductstatuseCustombatchCall<'a, C, NC, A> { + ProductstatuseCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `authinfo(...)`, `custombatch(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns information about the authenticated user. + pub fn authinfo(&self) -> AccountAuthinfoCall<'a, C, NC, A> { + AccountAuthinfoCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a Merchant Center account. This method supports patch semantics. + pub fn patch(&self, request: &Account, merchant_id: &str, account_id: &str) -> AccountPatchCall<'a, C, NC, A> { + AccountPatchCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a Merchant Center account. + pub fn get(&self, merchant_id: &str, account_id: &str) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a Merchant Center account. + pub fn update(&self, request: &Account, merchant_id: &str, account_id: &str) -> AccountUpdateCall<'a, C, NC, A> { + AccountUpdateCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the sub-accounts in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a Merchant Center sub-account. + pub fn delete(&self, merchant_id: &str, account_id: &str) -> AccountDeleteCall<'a, C, NC, A> { + AccountDeleteCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single request. + pub fn custombatch(&self, request: &AccountsCustomBatchRequest) -> AccountCustombatchCall<'a, C, NC, A> { + AccountCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a Merchant Center sub-account. + pub fn insert(&self, request: &Account, merchant_id: &str) -> AccountInsertCall<'a, C, NC, A> { + AccountInsertCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *inventory* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)` and `set(...)` +/// // to build up your call. +/// let rb = hub.inventory(); +/// # } +/// ``` +pub struct InventoryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for InventoryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> InventoryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates price and availability of a product in your Merchant Center account. + pub fn set(&self, request: &InventorySetRequest, merchant_id: &str, store_code: &str, product_id: &str) -> InventorySetCall<'a, C, NC, A> { + InventorySetCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _store_code: store_code.to_string(), + _product_id: product_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates price and availability for multiple products or stores in a single request. + pub fn custombatch(&self, request: &InventoryCustomBatchRequest) -> InventoryCustombatchCall<'a, C, NC, A> { + InventoryCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountstatuse* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.accountstatuses(); +/// # } +/// ``` +pub struct AccountstatuseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountstatuseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountstatuseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the status of a Merchant Center account. + pub fn get(&self, merchant_id: &str, account_id: &str) -> AccountstatuseGetCall<'a, C, NC, A> { + AccountstatuseGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the statuses of the sub-accounts in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> AccountstatuseListCall<'a, C, NC, A> { + AccountstatuseListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + pub fn custombatch(&self, request: &AccountstatusesCustomBatchRequest) -> AccountstatuseCustombatchCall<'a, C, NC, A> { + AccountstatuseCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *product* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.products(); +/// # } +/// ``` +pub struct ProductMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProductMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists the products in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> ProductListCall<'a, C, NC, A> { + ProductListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a product from your Merchant Center account. + pub fn get(&self, merchant_id: &str, product_id: &str) -> ProductGetCall<'a, C, NC, A> { + ProductGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _product_id: product_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a product from your Merchant Center account. + pub fn delete(&self, merchant_id: &str, product_id: &str) -> ProductDeleteCall<'a, C, NC, A> { + ProductDeleteCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _product_id: product_id.to_string(), + _dry_run: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves, inserts, and deletes multiple products in a single request. + pub fn custombatch(&self, request: &ProductsCustomBatchRequest) -> ProductCustombatchCall<'a, C, NC, A> { + ProductCustombatchCall { + hub: self.hub, + _request: request.clone(), + _dry_run: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Uploads a product to your Merchant Center account. + pub fn insert(&self, request: &Product, merchant_id: &str) -> ProductInsertCall<'a, C, NC, A> { + ProductInsertCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _dry_run: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountshipping* resources. +/// It is not used directly, but through the `ShoppingContent` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-content2" as content2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2::ShoppingContent; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `custombatch(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.accountshipping(); +/// # } +/// ``` +pub struct AccountshippingMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountshippingMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists the shipping settings of the sub-accounts in your Merchant Center account. + pub fn list(&self, merchant_id: &str) -> AccountshippingListCall<'a, C, NC, A> { + AccountshippingListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the shipping settings of the account. This method supports patch semantics. + pub fn patch(&self, request: &AccountShipping, merchant_id: &str, account_id: &str) -> AccountshippingPatchCall<'a, C, NC, A> { + AccountshippingPatchCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the shipping settings of the account. + pub fn update(&self, request: &AccountShipping, merchant_id: &str, account_id: &str) -> AccountshippingUpdateCall<'a, C, NC, A> { + AccountshippingUpdateCall { + hub: self.hub, + _request: request.clone(), + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves and updates the shipping settings of multiple accounts in a single request. + pub fn custombatch(&self, request: &AccountshippingCustomBatchRequest) -> AccountshippingCustombatchCall<'a, C, NC, A> { + AccountshippingCustombatchCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the shipping settings of the account. + pub fn get(&self, merchant_id: &str, account_id: &str) -> AccountshippingGetCall<'a, C, NC, A> { + AccountshippingGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _account_id: account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Retrieves and updates tax settings of multiple accounts in a single request. +/// +/// A builder for the *custombatch* method supported by a *accounttax* resource. +/// It is not used directly, but through a `AccounttaxMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccounttaxCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccounttaxCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounttax().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct AccounttaxCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccounttaxCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccounttaxCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccounttaxCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounttax.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/accounttax/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccounttaxCustomBatchRequest) -> AccounttaxCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccounttaxCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccounttaxCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccounttaxCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the tax settings of the account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *accounttax* resource. +/// It is not used directly, but through a `AccounttaxMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountTax; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountTax = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounttax().patch(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccounttaxPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountTax, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccounttaxPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountTax)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounttax.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounttax/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountTax) -> AccounttaxPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccounttaxPatchCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account tax settings. + pub fn account_id(mut self, new_value: &str) -> AccounttaxPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccounttaxPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccounttaxPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccounttaxPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the tax settings of the sub-accounts in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *accounttax* resource. +/// It is not used directly, but through a `AccounttaxMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounttax().list("merchantId") +/// .page_token("justo") +/// .max_results(100) +/// .doit(); +/// # } +/// ``` +pub struct AccounttaxListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccounttaxListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccounttaxListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounttax.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounttax".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccounttaxListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> AccounttaxListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of tax settings to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccounttaxListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccounttaxListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccounttaxListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccounttaxListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the tax settings of the account. +/// +/// A builder for the *update* method supported by a *accounttax* resource. +/// It is not used directly, but through a `AccounttaxMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountTax; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountTax = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounttax().update(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccounttaxUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountTax, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccounttaxUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountTax)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounttax.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounttax/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountTax) -> AccounttaxUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccounttaxUpdateCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account tax settings. + pub fn account_id(mut self, new_value: &str) -> AccounttaxUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccounttaxUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccounttaxUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccounttaxUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the tax settings of the account. +/// +/// A builder for the *get* method supported by a *accounttax* resource. +/// It is not used directly, but through a `AccounttaxMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounttax().get("merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccounttaxGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccounttaxGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccounttaxGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountTax)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounttax.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounttax/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccounttaxGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account tax settings. + pub fn account_id(mut self, new_value: &str) -> AccounttaxGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccounttaxGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccounttaxGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccounttaxGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the status of a datafeed from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *datafeedstatuse* resource. +/// It is not used directly, but through a `DatafeedstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeedstatuses().get("merchantId", "datafeedId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedstatuseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _datafeed_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedstatuseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedstatuseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatafeedStatus)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeedstatuses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("datafeedId", self._datafeed_id.to_string())); + for &field in ["alt", "merchantId", "datafeedId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeedstatuses/{datafeedId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{datafeedId}", "datafeedId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "datafeedId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedstatuseGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *datafeed id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn datafeed_id(mut self, new_value: &str) -> DatafeedstatuseGetCall<'a, C, NC, A> { + self._datafeed_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedstatuseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedstatuseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedstatuseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the statuses of the datafeeds in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *datafeedstatuse* resource. +/// It is not used directly, but through a `DatafeedstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeedstatuses().list("merchantId") +/// .page_token("aliquyam") +/// .max_results(35) +/// .doit(); +/// # } +/// ``` +pub struct DatafeedstatuseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedstatuseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedstatuseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatafeedstatusesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeedstatuses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeedstatuses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> DatafeedstatuseListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> DatafeedstatuseListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of products to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> DatafeedstatuseListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedstatuseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedstatuseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedstatuseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *custombatch* method supported by a *datafeedstatuse* resource. +/// It is not used directly, but through a `DatafeedstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::DatafeedstatusesCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DatafeedstatusesCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeedstatuses().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct DatafeedstatuseCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: DatafeedstatusesCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedstatuseCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedstatuseCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatafeedstatusesCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeedstatuses.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/datafeedstatuses/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DatafeedstatusesCustomBatchRequest) -> DatafeedstatuseCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedstatuseCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *custombatch* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::DatafeedsCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DatafeedsCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct DatafeedCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: DatafeedsCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatafeedsCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/datafeeds/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DatafeedsCustomBatchRequest) -> DatafeedCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a datafeed from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().get("merchantId", "datafeedId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _datafeed_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Datafeed)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("datafeedId", self._datafeed_id.to_string())); + for &field in ["alt", "merchantId", "datafeedId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds/{datafeedId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{datafeedId}", "datafeedId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "datafeedId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *datafeed id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn datafeed_id(mut self, new_value: &str) -> DatafeedGetCall<'a, C, NC, A> { + self._datafeed_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a datafeed of your Merchant Center account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Datafeed; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Datafeed = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().patch(&req, "merchantId", "datafeedId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Datafeed, + _merchant_id: String, + _datafeed_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Datafeed)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("datafeedId", self._datafeed_id.to_string())); + for &field in ["alt", "merchantId", "datafeedId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds/{datafeedId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{datafeedId}", "datafeedId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "datafeedId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Datafeed) -> DatafeedPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedPatchCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *datafeed id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn datafeed_id(mut self, new_value: &str) -> DatafeedPatchCall<'a, C, NC, A> { + self._datafeed_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a datafeed from your Merchant Center account. +/// +/// A builder for the *delete* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().delete("merchantId", "datafeedId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _datafeed_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("datafeedId", self._datafeed_id.to_string())); + for &field in ["merchantId", "datafeedId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds/{datafeedId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{datafeedId}", "datafeedId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "datafeedId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedDeleteCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *datafeed id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn datafeed_id(mut self, new_value: &str) -> DatafeedDeleteCall<'a, C, NC, A> { + self._datafeed_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Registers a datafeed with your Merchant Center account. +/// +/// A builder for the *insert* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Datafeed; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Datafeed = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().insert(&req, "merchantId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Datafeed, + _merchant_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Datafeed)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + for &field in ["alt", "merchantId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Datafeed) -> DatafeedInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedInsertCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the datafeeds in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().list("merchantId") +/// .page_token("et") +/// .max_results(31) +/// .doit(); +/// # } +/// ``` +pub struct DatafeedListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DatafeedsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> DatafeedListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> DatafeedListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of products to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> DatafeedListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a datafeed of your Merchant Center account. +/// +/// A builder for the *update* method supported by a *datafeed* resource. +/// It is not used directly, but through a `DatafeedMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Datafeed; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Datafeed = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datafeeds().update(&req, "merchantId", "datafeedId") +/// .doit(); +/// # } +/// ``` +pub struct DatafeedUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Datafeed, + _merchant_id: String, + _datafeed_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatafeedUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatafeedUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Datafeed)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.datafeeds.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("datafeedId", self._datafeed_id.to_string())); + for &field in ["alt", "merchantId", "datafeedId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/datafeeds/{datafeedId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{datafeedId}", "datafeedId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "datafeedId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Datafeed) -> DatafeedUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn merchant_id(mut self, new_value: &str) -> DatafeedUpdateCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *datafeed id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn datafeed_id(mut self, new_value: &str) -> DatafeedUpdateCall<'a, C, NC, A> { + self._datafeed_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatafeedUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatafeedUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatafeedUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the status of a product from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *productstatuse* resource. +/// It is not used directly, but through a `ProductstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.productstatuses().get("merchantId", "productId") +/// .doit(); +/// # } +/// ``` +pub struct ProductstatuseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _product_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductstatuseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductstatuseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductStatus)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.productstatuses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("productId", self._product_id.to_string())); + for &field in ["alt", "merchantId", "productId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/productstatuses/{productId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductstatuseGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductstatuseGetCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductstatuseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductstatuseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductstatuseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the statuses of the products in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *productstatuse* resource. +/// It is not used directly, but through a `ProductstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.productstatuses().list("merchantId") +/// .page_token("sadipscing") +/// .max_results(53) +/// .doit(); +/// # } +/// ``` +pub struct ProductstatuseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductstatuseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductstatuseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductstatusesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.productstatuses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/productstatuses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductstatuseListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> ProductstatuseListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of product statuses to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> ProductstatuseListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductstatuseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductstatuseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductstatuseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the statuses of multiple products in a single request. +/// +/// A builder for the *custombatch* method supported by a *productstatuse* resource. +/// It is not used directly, but through a `ProductstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::ProductstatusesCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProductstatusesCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.productstatuses().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct ProductstatuseCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: ProductstatusesCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductstatuseCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductstatuseCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductstatusesCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.productstatuses.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/productstatuses/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProductstatusesCustomBatchRequest) -> ProductstatuseCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductstatuseCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns information about the authenticated user. +/// +/// A builder for the *authinfo* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().authinfo() +/// .doit(); +/// # } +/// ``` +pub struct AccountAuthinfoCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountAuthinfoCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountAuthinfoCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountsAuthInfoResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.authinfo", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/accounts/authinfo".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAuthinfoCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountAuthinfoCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAuthinfoCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a Merchant Center account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().patch(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Account, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountPatchCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account. + pub fn account_id(mut self, new_value: &str) -> AccountPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a Merchant Center account. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get("merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account. + pub fn account_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a Merchant Center account. +/// +/// A builder for the *update* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().update(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Account, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountUpdateCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account. + pub fn account_id(mut self, new_value: &str) -> AccountUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the sub-accounts in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list("merchantId") +/// .page_token("invidunt") +/// .max_results(19) +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of accounts to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a Merchant Center sub-account. +/// +/// A builder for the *delete* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().delete("merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountDeleteCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account. + pub fn account_id(mut self, new_value: &str) -> AccountDeleteCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves, inserts, updates, and deletes multiple Merchant Center (sub-)accounts in a single request. +/// +/// A builder for the *custombatch* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountsCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountsCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct AccountCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountsCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountsCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/accounts/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountsCustomBatchRequest) -> AccountCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a Merchant Center sub-account. +/// +/// A builder for the *insert* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().insert(&req, "merchantId") +/// .doit(); +/// # } +/// ``` +pub struct AccountInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Account, + _merchant_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accounts.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + for &field in ["alt", "merchantId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountInsertCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates price and availability of a product in your Merchant Center account. +/// +/// A builder for the *set* method supported by a *inventory* resource. +/// It is not used directly, but through a `InventoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::InventorySetRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InventorySetRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inventory().set(&req, "merchantId", "storeCode", "productId") +/// .doit(); +/// # } +/// ``` +pub struct InventorySetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: InventorySetRequest, + _merchant_id: String, + _store_code: String, + _product_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InventorySetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InventorySetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InventorySetResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.inventory.set", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("storeCode", self._store_code.to_string())); + params.push(("productId", self._product_id.to_string())); + for &field in ["alt", "merchantId", "storeCode", "productId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/inventory/{storeCode}/products/{productId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{storeCode}", "storeCode"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["merchantId", "storeCode", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InventorySetRequest) -> InventorySetCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> InventorySetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *store code* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The code of the store for which to update price and availability. Use online to update price and availability of an online product. + pub fn store_code(mut self, new_value: &str) -> InventorySetCall<'a, C, NC, A> { + self._store_code = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product for which to update price and availability. + pub fn product_id(mut self, new_value: &str) -> InventorySetCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InventorySetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InventorySetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InventorySetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates price and availability for multiple products or stores in a single request. +/// +/// A builder for the *custombatch* method supported by a *inventory* resource. +/// It is not used directly, but through a `InventoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::InventoryCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: InventoryCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.inventory().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct InventoryCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: InventoryCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for InventoryCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> InventoryCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InventoryCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.inventory.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/inventory/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &InventoryCustomBatchRequest) -> InventoryCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InventoryCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InventoryCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InventoryCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the status of a Merchant Center account. +/// +/// A builder for the *get* method supported by a *accountstatuse* resource. +/// It is not used directly, but through a `AccountstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountstatuses().get("merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountstatuseGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountstatuseGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountstatuseGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountStatus)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountstatuses.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountstatuses/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountstatuseGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account. + pub fn account_id(mut self, new_value: &str) -> AccountstatuseGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountstatuseGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountstatuseGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountstatuseGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the statuses of the sub-accounts in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *accountstatuse* resource. +/// It is not used directly, but through a `AccountstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountstatuses().list("merchantId") +/// .page_token("amet") +/// .max_results(78) +/// .doit(); +/// # } +/// ``` +pub struct AccountstatuseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountstatuseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountstatuseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountstatusesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountstatuses.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountstatuses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountstatuseListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> AccountstatuseListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of account statuses to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountstatuseListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountstatuseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountstatuseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountstatuseListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// A builder for the *custombatch* method supported by a *accountstatuse* resource. +/// It is not used directly, but through a `AccountstatuseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountstatusesCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountstatusesCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountstatuses().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct AccountstatuseCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountstatusesCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountstatuseCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountstatuseCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountstatusesCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountstatuses.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/accountstatuses/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountstatusesCustomBatchRequest) -> AccountstatuseCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountstatuseCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountstatuseCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the products in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().list("merchantId") +/// .page_token("ut") +/// .max_results(85) +/// .doit(); +/// # } +/// ``` +pub struct ProductListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.products.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/products".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> ProductListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of products to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> ProductListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a product from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().get("merchantId", "productId") +/// .doit(); +/// # } +/// ``` +pub struct ProductGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _product_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Product)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.products.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("productId", self._product_id.to_string())); + for &field in ["alt", "merchantId", "productId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/products/{productId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductGetCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a product from your Merchant Center account. +/// +/// A builder for the *delete* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().delete("merchantId", "productId") +/// .dry_run(true) +/// .doit(); +/// # } +/// ``` +pub struct ProductDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _product_id: String, + _dry_run: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.products.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("productId", self._product_id.to_string())); + if let Some(value) = self._dry_run { + params.push(("dryRun", value.to_string())); + } + for &field in ["merchantId", "productId", "dryRun"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/products/{productId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{productId}", "productId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "productId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductDeleteCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *product id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the product. + pub fn product_id(mut self, new_value: &str) -> ProductDeleteCall<'a, C, NC, A> { + self._product_id = new_value.to_string(); + self + } + /// Sets the *dry run* query property to the given value. + /// + /// + /// Flag to run the request in dry-run mode. + pub fn dry_run(mut self, new_value: bool) -> ProductDeleteCall<'a, C, NC, A> { + self._dry_run = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves, inserts, and deletes multiple products in a single request. +/// +/// A builder for the *custombatch* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::ProductsCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ProductsCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().custombatch(&req) +/// .dry_run(false) +/// .doit(); +/// # } +/// ``` +pub struct ProductCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: ProductsCustomBatchRequest, + _dry_run: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductsCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.products.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + if let Some(value) = self._dry_run { + params.push(("dryRun", value.to_string())); + } + for &field in ["alt", "dryRun"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/products/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ProductsCustomBatchRequest) -> ProductCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dry run* query property to the given value. + /// + /// + /// Flag to run the request in dry-run mode. + pub fn dry_run(mut self, new_value: bool) -> ProductCustombatchCall<'a, C, NC, A> { + self._dry_run = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Uploads a product to your Merchant Center account. +/// +/// A builder for the *insert* method supported by a *product* resource. +/// It is not used directly, but through a `ProductMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::Product; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Product = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.products().insert(&req, "merchantId") +/// .dry_run(true) +/// .doit(); +/// # } +/// ``` +pub struct ProductInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: Product, + _merchant_id: String, + _dry_run: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProductInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProductInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Product)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.products.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._dry_run { + params.push(("dryRun", value.to_string())); + } + for &field in ["alt", "merchantId", "dryRun"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/products".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Product) -> ProductInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> ProductInsertCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *dry run* query property to the given value. + /// + /// + /// Flag to run the request in dry-run mode. + pub fn dry_run(mut self, new_value: bool) -> ProductInsertCall<'a, C, NC, A> { + self._dry_run = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProductInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProductInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProductInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the shipping settings of the sub-accounts in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *accountshipping* resource. +/// It is not used directly, but through a `AccountshippingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountshipping().list("merchantId") +/// .page_token("gubergren") +/// .max_results(81) +/// .doit(); +/// # } +/// ``` +pub struct AccountshippingListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountshippingListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountshippingListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountshipping.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "merchantId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountshipping".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["merchantId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountshippingListCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The token returned by the previous request. + pub fn page_token(mut self, new_value: &str) -> AccountshippingListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of shipping settings to return in the response, used for paging. + pub fn max_results(mut self, new_value: u32) -> AccountshippingListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountshippingListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountshippingListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountshippingListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the shipping settings of the account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *accountshipping* resource. +/// It is not used directly, but through a `AccountshippingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountShipping; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountShipping = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountshipping().patch(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountshippingPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountShipping, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountshippingPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountShipping)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountshipping.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountshipping/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountShipping) -> AccountshippingPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountshippingPatchCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account shipping settings. + pub fn account_id(mut self, new_value: &str) -> AccountshippingPatchCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountshippingPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountshippingPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountshippingPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the shipping settings of the account. +/// +/// A builder for the *update* method supported by a *accountshipping* resource. +/// It is not used directly, but through a `AccountshippingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountShipping; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountShipping = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountshipping().update(&req, "merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountshippingUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountShipping, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountshippingUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountShipping)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountshipping.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountshipping/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountShipping) -> AccountshippingUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountshippingUpdateCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account shipping settings. + pub fn account_id(mut self, new_value: &str) -> AccountshippingUpdateCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountshippingUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountshippingUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountshippingUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves and updates the shipping settings of multiple accounts in a single request. +/// +/// A builder for the *custombatch* method supported by a *accountshipping* resource. +/// It is not used directly, but through a `AccountshippingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// use content2::AccountshippingCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountshippingCustomBatchRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountshipping().custombatch(&req) +/// .doit(); +/// # } +/// ``` +pub struct AccountshippingCustombatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: AccountshippingCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountshippingCustombatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingCustombatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountshippingCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountshipping.custombatch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/accountshipping/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountshippingCustomBatchRequest) -> AccountshippingCustombatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountshippingCustombatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountshippingCustombatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountshippingCustombatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the shipping settings of the account. +/// +/// A builder for the *get* method supported by a *accountshipping* resource. +/// It is not used directly, but through a `AccountshippingMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-content2" as content2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2::ShoppingContent; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = ShoppingContent::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accountshipping().get("merchantId", "accountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountshippingGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountshippingGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountshippingGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountShipping)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "content.accountshipping.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + params.push(("accountId", self._account_id.to_string())); + for &field in ["alt", "merchantId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/content/v2/{merchantId}/accountshipping/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{accountId}", "accountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantId", "accountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *merchant id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the managing account. + pub fn merchant_id(mut self, new_value: &str) -> AccountshippingGetCall<'a, C, NC, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Sets the *account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the account for which to get/update account shipping settings. + pub fn account_id(mut self, new_value: &str) -> AccountshippingGetCall<'a, C, NC, A> { + self._account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountshippingGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountshippingGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountshippingGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/coordinate1/Cargo.toml b/gen/coordinate1/Cargo.toml new file mode 100644 index 0000000000..0657c6abb0 --- /dev/null +++ b/gen/coordinate1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-coordinate1" +version = "0.1.0+20141215" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with coordinate (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/coordinate1" +homepage = "https://developers.google.com/coordinate/" +documentation = "http://byron.github.io/google-apis-rs/google-coordinate1" +license = "MIT" +keywords = ["coordinate", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/coordinate1/LICENSE.md b/gen/coordinate1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/coordinate1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/coordinate1/README.md b/gen/coordinate1/README.md new file mode 100644 index 0000000000..cf686eb8a7 --- /dev/null +++ b/gen/coordinate1/README.md @@ -0,0 +1,193 @@ + +The `google-coordinate1` library allows access to all features of the *Google coordinate* service. + +This documentation was generated from *coordinate* crate version *0.1.0+20141215*, where *20141215* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *coordinate* *v1* API can be found at the +[official documentation site](https://developers.google.com/coordinate/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Coordinate.html) ... + +* [custom field def](http://byron.github.io/google-apis-rs/google-coordinate1/struct.CustomFieldDef.html) + * [*list*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.CustomFieldDefListCall.html) +* [jobs](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Job.html) + * [*get*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.JobGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.JobInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.JobListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.JobPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.JobUpdateCall.html) +* [location](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Location.html) + * [*list*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.LocationListCall.html) +* [schedule](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Schedule.html) + * [*get*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.ScheduleGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.SchedulePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.ScheduleUpdateCall.html) +* [team](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Team.html) + * [*list*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.TeamListCall.html) +* [worker](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Worker.html) + * [*list*](http://byron.github.io/google-apis-rs/google-coordinate1/struct.WorkerListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-coordinate1/struct.Coordinate.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-coordinate1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.jobs().get(...).doit() +let r = hub.jobs().update(...).doit() +let r = hub.jobs().patch(...).doit() +let r = hub.jobs().list(...).doit() +let r = hub.jobs().insert(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-coordinate1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-coordinate1" as coordinate1; +use coordinate1::Job; +use coordinate1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use coordinate1::Coordinate; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Coordinate::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: Job = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.jobs().update(&req, "teamId", "jobId") + .title("Stet") + .progress("sed") + .note("et") + .lng(0.824373746908) + .lat(0.383704808614) + .customer_phone_number("accusam") + .customer_name("takimata") + .add_custom_field("justo") + .assignee("amet.") + .address("erat") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-coordinate1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-coordinate1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-coordinate1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-coordinate1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-coordinate1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-coordinate1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-coordinate1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-coordinate1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-coordinate1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-coordinate1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **coordinate1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/coordinate1/src/cmn.rs b/gen/coordinate1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/coordinate1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/coordinate1/src/lib.rs b/gen/coordinate1/src/lib.rs new file mode 100644 index 0000000000..d95e4de771 --- /dev/null +++ b/gen/coordinate1/src/lib.rs @@ -0,0 +1,4801 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *coordinate* crate version *0.1.0+20141215*, where *20141215* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *coordinate* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/coordinate/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/coordinate1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Coordinate.html) ... +//! +//! * [custom field def](struct.CustomFieldDef.html) +//! * [*list*](struct.CustomFieldDefListCall.html) +//! * [jobs](struct.Job.html) +//! * [*get*](struct.JobGetCall.html), [*insert*](struct.JobInsertCall.html), [*list*](struct.JobListCall.html), [*patch*](struct.JobPatchCall.html) and [*update*](struct.JobUpdateCall.html) +//! * [location](struct.Location.html) +//! * [*list*](struct.LocationListCall.html) +//! * [schedule](struct.Schedule.html) +//! * [*get*](struct.ScheduleGetCall.html), [*patch*](struct.SchedulePatchCall.html) and [*update*](struct.ScheduleUpdateCall.html) +//! * [team](struct.Team.html) +//! * [*list*](struct.TeamListCall.html) +//! * [worker](struct.Worker.html) +//! * [*list*](struct.WorkerListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Coordinate.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.jobs().get(...).doit() +//! let r = hub.jobs().update(...).doit() +//! let r = hub.jobs().patch(...).doit() +//! let r = hub.jobs().list(...).doit() +//! let r = hub.jobs().insert(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-coordinate1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-coordinate1" as coordinate1; +//! use coordinate1::Job; +//! use coordinate1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use coordinate1::Coordinate; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Coordinate::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: Job = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.jobs().update(&req, "teamId", "jobId") +//! .title("nonumy") +//! .progress("dolores") +//! .note("gubergren") +//! .lng(0.0653431304201) +//! .lat(0.699208331616) +//! .customer_phone_number("ea") +//! .customer_name("no") +//! .add_custom_field("justo") +//! .assignee("justo") +//! .address("et") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your Google Maps Coordinate jobs + Full, + + /// View your Google Coordinate jobs + Readonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/coordinate", + Scope::Readonly => "https://www.googleapis.com/auth/coordinate.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Coordinate related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Job; +/// use coordinate1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Job = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().update(&req, "teamId", "jobId") +/// .title("ipsum") +/// .progress("Lorem") +/// .note("et") +/// .lng(0.313727897996) +/// .lat(0.69054137112) +/// .customer_phone_number("sea") +/// .customer_name("Lorem") +/// .add_custom_field("eos") +/// .assignee("erat") +/// .address("sadipscing") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Coordinate { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Coordinate {} + +impl<'a, C, NC, A> Coordinate + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Coordinate { + Coordinate { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn custom_field_def(&'a self) -> CustomFieldDefMethods<'a, C, NC, A> { + CustomFieldDefMethods { hub: &self } + } + pub fn jobs(&'a self) -> JobMethods<'a, C, NC, A> { + JobMethods { hub: &self } + } + pub fn location(&'a self) -> LocationMethods<'a, C, NC, A> { + LocationMethods { hub: &self } + } + pub fn schedule(&'a self) -> ScheduleMethods<'a, C, NC, A> { + ScheduleMethods { hub: &self } + } + pub fn team(&'a self) -> TeamMethods<'a, C, NC, A> { + TeamMethods { hub: &self } + } + pub fn worker(&'a self) -> WorkerMethods<'a, C, NC, A> { + WorkerMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Response from a List Locations request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list location](struct.LocationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct LocationListResponse { + /// A token to provide to get the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Locations in the collection. + pub items: Vec, + /// Identifies this object as a list of locations. + pub kind: String, + /// Pagination information for token pagination. + #[serde(alias="tokenPagination")] + pub token_pagination: TokenPagination, +} + +impl ResponseResult for LocationListResponse {} + + +/// Change to a job. For example assigning the job to a different worker. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobChange { + /// Time at which this change was applied. + pub timestamp: String, + /// Identifies this object as a job change. + pub kind: String, + /// Change applied to the job. Only the fields that were changed are set. + pub state: JobState, +} + +impl Part for JobChange {} + + +/// Enum Item definition. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EnumItemDef { + /// Whether the enum item is active. Jobs may contain inactive enum values; however, setting an enum to an inactive value when creating or updating a job will result in a 500 error. + pub active: bool, + /// Identifies this object as an enum item definition. + pub kind: String, + /// Custom field value. + pub value: String, +} + +impl Part for EnumItemDef {} + + +/// Collection of custom field definitions for a team. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list custom field def](struct.CustomFieldDefListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomFieldDefListResponse { + /// Collection of custom field definitions in a team. + pub items: Vec, + /// Identifies this object as a collection of custom field definitions in a team. + pub kind: String, +} + +impl ResponseResult for CustomFieldDefListResponse {} + + +/// Pagination information. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TokenPagination { + /// A token to provide to get the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// A token to provide to get the previous page of results. + #[serde(alias="previousPageToken")] + pub previous_page_token: String, + /// Identifies this object as pagination information. + pub kind: String, +} + +impl Part for TokenPagination {} + + +/// Location of a job. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Location { + /// Latitude. + pub lat: f64, + /// Identifies this object as a location. + pub kind: String, + /// Address. + #[serde(alias="addressLine")] + pub address_line: Vec, + /// Longitude. + pub lng: f64, +} + +impl Part for Location {} + + +/// A Coordinate team. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Team { + /// Identifies this object as a team. + pub kind: String, + /// Team id, as found in a coordinate team url e.g. https://coordinate.google.com/f/xyz where "xyz" is the team id. + pub id: String, + /// Team name + pub name: String, +} + +impl Part for Team {} + + +/// Current state of a job. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct JobState { + /// Identifies this object as a job state. + pub kind: String, + /// Customer name. + #[serde(alias="customerName")] + pub customer_name: String, + /// Job title. + pub title: String, + /// Note added to the job. + pub note: Vec, + /// Email address of the assignee, or the string "DELETED_USER" if the account is no longer available. + pub assignee: String, + /// Customer phone number. + #[serde(alias="customerPhoneNumber")] + pub customer_phone_number: String, + /// Job location. + pub location: Location, + /// Job progress. + pub progress: String, + /// Custom fields. + #[serde(alias="customFields")] + pub custom_fields: CustomFields, +} + +impl Part for JobState {} + + +/// Collection of custom fields. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomFields { + /// Identifies this object as a collection of custom fields. + pub kind: String, + /// Collection of custom fields. + #[serde(alias="customField")] + pub custom_field: Vec, +} + +impl Part for CustomFields {} + + +/// Response from a List Workers request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list worker](struct.WorkerListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct WorkerListResponse { + /// Workers in the collection. + pub items: Vec, + /// Identifies this object as a list of workers. + pub kind: String, +} + +impl ResponseResult for WorkerListResponse {} + + +/// Recorded location of a worker. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct LocationRecord { + /// Latitude. + pub latitude: f64, + /// The collection time in milliseconds since the epoch. + #[serde(alias="collectionTime")] + pub collection_time: String, + /// The location accuracy in meters. This is the radius of a 95% confidence interval around the location measurement. + #[serde(alias="confidenceRadius")] + pub confidence_radius: f64, + /// Identifies this object as a location. + pub kind: String, + /// Longitude. + pub longitude: f64, +} + +impl Part for LocationRecord {} + + +/// Job schedule. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update schedule](struct.ScheduleUpdateCall.html) (request|response) +/// * [patch schedule](struct.SchedulePatchCall.html) (request|response) +/// * [get schedule](struct.ScheduleGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Schedule { + /// Job duration in milliseconds. + pub duration: Option, + /// Identifies this object as a job schedule. + pub kind: Option, + /// Whether the job is scheduled for the whole day. Time of day in start/end times is ignored if this is true. + #[serde(alias="allDay")] + pub all_day: Option, + /// Scheduled start time in milliseconds since epoch. + #[serde(alias="startTime")] + pub start_time: Option, + /// Scheduled end time in milliseconds since epoch. + #[serde(alias="endTime")] + pub end_time: Option, +} + +impl RequestValue for Schedule {} +impl ResponseResult for Schedule {} + + +/// Response from a List Teams request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list team](struct.TeamListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TeamListResponse { + /// Teams in the collection. + pub items: Vec, + /// Identifies this object as a list of teams. + pub kind: String, +} + +impl ResponseResult for TeamListResponse {} + + +/// Response from a List Jobs request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list jobs](struct.JobListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct JobListResponse { + /// A token to provide to get the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Jobs in the collection. + pub items: Vec, + /// Identifies this object as a list of jobs. + pub kind: String, +} + +impl ResponseResult for JobListResponse {} + + +/// A worker in a Coordinate team. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Worker { + /// Identifies this object as a worker. + pub kind: String, + /// Worker email address. If a worker has been deleted from your team, the email address will appear as DELETED_USER. + pub id: String, +} + +impl Part for Worker {} + + +/// A job. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get jobs](struct.JobGetCall.html) (response) +/// * [update jobs](struct.JobUpdateCall.html) (request|response) +/// * [patch jobs](struct.JobPatchCall.html) (request|response) +/// * [list jobs](struct.JobListCall.html) (none) +/// * [insert jobs](struct.JobInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Job { + /// Identifies this object as a job. + pub kind: Option, + /// List of job changes since it was created. The first change corresponds to the state of the job when it was created. + #[serde(alias="jobChange")] + pub job_change: Option>, + /// Job id. + pub id: Option, + /// Current job state. + pub state: Option, +} + +impl RequestValue for Job {} +impl Resource for Job {} +impl ResponseResult for Job {} + + +/// Custom field definition. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CustomFieldDef { + /// Identifies this object as a custom field definition. + pub kind: String, + /// List of enum items for this custom field. Populated only if the field type is enum. Enum fields appear as 'lists' in the Coordinate web and mobile UI. + pub enumitems: Vec, + /// Custom field name. + pub name: String, + /// Custom field type. + #[serde(alias="type")] + pub type_: String, + /// Whether the field is required for checkout. + #[serde(alias="requiredForCheckout")] + pub required_for_checkout: bool, + /// Whether the field is enabled. + pub enabled: bool, + /// Custom field id. + pub id: String, +} + +impl Part for CustomFieldDef {} + + +/// Custom field. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomField { + /// Identifies this object as a custom field. + pub kind: String, + /// Custom field id. + #[serde(alias="customFieldId")] + pub custom_field_id: String, + /// Custom field value. + pub value: String, +} + +impl Part for CustomField {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *job* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.jobs(); +/// # } +/// ``` +pub struct JobMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for JobMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a job, including all the changes made to the job. + pub fn get(&self, team_id: &str, job_id: &str) -> JobGetCall<'a, C, NC, A> { + JobGetCall { + hub: self.hub, + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a job. Fields that are set in the job state will be updated. + pub fn update(&self, request: &Job, team_id: &str, job_id: &str) -> JobUpdateCall<'a, C, NC, A> { + JobUpdateCall { + hub: self.hub, + _request: request.clone(), + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _title: Default::default(), + _progress: Default::default(), + _note: Default::default(), + _lng: Default::default(), + _lat: Default::default(), + _customer_phone_number: Default::default(), + _customer_name: Default::default(), + _custom_field: Default::default(), + _assignee: Default::default(), + _address: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a job. Fields that are set in the job state will be updated. This method supports patch semantics. + pub fn patch(&self, request: &Job, team_id: &str, job_id: &str) -> JobPatchCall<'a, C, NC, A> { + JobPatchCall { + hub: self.hub, + _request: request.clone(), + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _title: Default::default(), + _progress: Default::default(), + _note: Default::default(), + _lng: Default::default(), + _lat: Default::default(), + _customer_phone_number: Default::default(), + _customer_name: Default::default(), + _custom_field: Default::default(), + _assignee: Default::default(), + _address: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves jobs created or modified since the given timestamp. + pub fn list(&self, team_id: &str) -> JobListCall<'a, C, NC, A> { + JobListCall { + hub: self.hub, + _team_id: team_id.to_string(), + _page_token: Default::default(), + _min_modified_timestamp_ms: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new job. Only the state field of the job should be set. + pub fn insert(&self, request: &Job, team_id: &str, address: &str, lat: f64, lng: f64, title: &str) -> JobInsertCall<'a, C, NC, A> { + JobInsertCall { + hub: self.hub, + _request: request.clone(), + _team_id: team_id.to_string(), + _address: address.to_string(), + _lat: lat, + _lng: lng, + _title: title.to_string(), + _note: Default::default(), + _customer_phone_number: Default::default(), + _customer_name: Default::default(), + _custom_field: Default::default(), + _assignee: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *schedule* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.schedule(); +/// # } +/// ``` +pub struct ScheduleMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ScheduleMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ScheduleMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Replaces the schedule of a job with the provided schedule. + pub fn update(&self, request: &Schedule, team_id: &str, job_id: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + ScheduleUpdateCall { + hub: self.hub, + _request: request.clone(), + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _start_time: Default::default(), + _end_time: Default::default(), + _duration: Default::default(), + _all_day: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Replaces the schedule of a job with the provided schedule. This method supports patch semantics. + pub fn patch(&self, request: &Schedule, team_id: &str, job_id: &str) -> SchedulePatchCall<'a, C, NC, A> { + SchedulePatchCall { + hub: self.hub, + _request: request.clone(), + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _start_time: Default::default(), + _end_time: Default::default(), + _duration: Default::default(), + _all_day: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the schedule for a job. + pub fn get(&self, team_id: &str, job_id: &str) -> ScheduleGetCall<'a, C, NC, A> { + ScheduleGetCall { + hub: self.hub, + _team_id: team_id.to_string(), + _job_id: job_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *worker* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.worker(); +/// # } +/// ``` +pub struct WorkerMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for WorkerMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> WorkerMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of workers in a team. + pub fn list(&self, team_id: &str) -> WorkerListCall<'a, C, NC, A> { + WorkerListCall { + hub: self.hub, + _team_id: team_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *location* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.location(); +/// # } +/// ``` +pub struct LocationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for LocationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> LocationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of locations for a worker. + pub fn list(&self, team_id: &str, worker_email: &str, start_timestamp_ms: &str) -> LocationListCall<'a, C, NC, A> { + LocationListCall { + hub: self.hub, + _team_id: team_id.to_string(), + _worker_email: worker_email.to_string(), + _start_timestamp_ms: start_timestamp_ms.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *team* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.team(); +/// # } +/// ``` +pub struct TeamMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TeamMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TeamMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of teams for a user. + pub fn list(&self) -> TeamListCall<'a, C, NC, A> { + TeamListCall { + hub: self.hub, + _worker: Default::default(), + _dispatcher: Default::default(), + _admin: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *customFieldDef* resources. +/// It is not used directly, but through the `Coordinate` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-coordinate1" as coordinate1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use coordinate1::Coordinate; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.custom_field_def(); +/// # } +/// ``` +pub struct CustomFieldDefMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CustomFieldDefMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomFieldDefMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of custom field definitions for a team. + pub fn list(&self, team_id: &str) -> CustomFieldDefListCall<'a, C, NC, A> { + CustomFieldDefListCall { + hub: self.hub, + _team_id: team_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Retrieves a job, including all the changes made to the job. +/// +/// A builder for the *get* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().get("teamId", "jobId") +/// .doit(); +/// # } +/// ``` +pub struct JobGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _job_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Job)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.jobs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + for &field in ["alt", "teamId", "jobId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> JobGetCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> JobGetCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a job. Fields that are set in the job state will be updated. +/// +/// A builder for the *update* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Job; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Job = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().update(&req, "teamId", "jobId") +/// .title("no") +/// .progress("labore") +/// .note("eirmod") +/// .lng(0.675598874816) +/// .lat(0.634997883415) +/// .customer_phone_number("aliquyam") +/// .customer_name("accusam") +/// .add_custom_field("Lorem") +/// .assignee("sea") +/// .address("et") +/// .doit(); +/// # } +/// ``` +pub struct JobUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _request: Job, + _team_id: String, + _job_id: String, + _title: Option, + _progress: Option, + _note: Option, + _lng: Option, + _lat: Option, + _customer_phone_number: Option, + _customer_name: Option, + _custom_field: Vec, + _assignee: Option, + _address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Job)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.jobs.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._title { + params.push(("title", value.to_string())); + } + if let Some(value) = self._progress { + params.push(("progress", value.to_string())); + } + if let Some(value) = self._note { + params.push(("note", value.to_string())); + } + if let Some(value) = self._lng { + params.push(("lng", value.to_string())); + } + if let Some(value) = self._lat { + params.push(("lat", value.to_string())); + } + if let Some(value) = self._customer_phone_number { + params.push(("customerPhoneNumber", value.to_string())); + } + if let Some(value) = self._customer_name { + params.push(("customerName", value.to_string())); + } + if self._custom_field.len() > 0 { + let mut s = String::new(); + for f in self._custom_field.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("customField", s)); + } + if let Some(value) = self._assignee { + params.push(("assignee", value.to_string())); + } + if let Some(value) = self._address { + params.push(("address", value.to_string())); + } + for &field in ["alt", "teamId", "jobId", "title", "progress", "note", "lng", "lat", "customerPhoneNumber", "customerName", "customField", "assignee", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Job) -> JobUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *title* query property to the given value. + /// + /// + /// Job title + pub fn title(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._title = Some(new_value.to_string()); + self + } + /// Sets the *progress* query property to the given value. + /// + /// + /// Job progress + pub fn progress(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._progress = Some(new_value.to_string()); + self + } + /// Sets the *note* query property to the given value. + /// + /// + /// Job note as newline (Unix) separated string + pub fn note(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._note = Some(new_value.to_string()); + self + } + /// Sets the *lng* query property to the given value. + /// + /// + /// The longitude coordinate of this job's location. + pub fn lng(mut self, new_value: f64) -> JobUpdateCall<'a, C, NC, A> { + self._lng = Some(new_value); + self + } + /// Sets the *lat* query property to the given value. + /// + /// + /// The latitude coordinate of this job's location. + pub fn lat(mut self, new_value: f64) -> JobUpdateCall<'a, C, NC, A> { + self._lat = Some(new_value); + self + } + /// Sets the *customer phone number* query property to the given value. + /// + /// + /// Customer phone number + pub fn customer_phone_number(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._customer_phone_number = Some(new_value.to_string()); + self + } + /// Sets the *customer name* query property to the given value. + /// + /// + /// Customer name + pub fn customer_name(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._customer_name = Some(new_value.to_string()); + self + } + /// Append the given value to the *custom field* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Sets the value of custom fields. To set a custom field, pass the field id (from /team/teamId/custom_fields), a URL escaped '=' character, and the desired value as a parameter. For example, customField=12%3DAlice. Repeat the parameter for each custom field. Note that '=' cannot appear in the parameter value. Specifying an invalid, or inactive enum field will result in an error 500. + pub fn add_custom_field(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._custom_field.push(new_value.to_string()); + self + } + /// Sets the *assignee* query property to the given value. + /// + /// + /// Assignee email address, or empty string to unassign. + pub fn assignee(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._assignee = Some(new_value.to_string()); + self + } + /// Sets the *address* query property to the given value. + /// + /// + /// Job address as newline (Unix) separated string + pub fn address(mut self, new_value: &str) -> JobUpdateCall<'a, C, NC, A> { + self._address = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a job. Fields that are set in the job state will be updated. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Job; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Job = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().patch(&req, "teamId", "jobId") +/// .title("eirmod") +/// .progress("sanctus") +/// .note("et") +/// .lng(0.549609244211) +/// .lat(0.77599682643) +/// .customer_phone_number("consetetur") +/// .customer_name("ut") +/// .add_custom_field("ea") +/// .assignee("sed") +/// .address("dolor") +/// .doit(); +/// # } +/// ``` +pub struct JobPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _request: Job, + _team_id: String, + _job_id: String, + _title: Option, + _progress: Option, + _note: Option, + _lng: Option, + _lat: Option, + _customer_phone_number: Option, + _customer_name: Option, + _custom_field: Vec, + _assignee: Option, + _address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Job)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.jobs.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._title { + params.push(("title", value.to_string())); + } + if let Some(value) = self._progress { + params.push(("progress", value.to_string())); + } + if let Some(value) = self._note { + params.push(("note", value.to_string())); + } + if let Some(value) = self._lng { + params.push(("lng", value.to_string())); + } + if let Some(value) = self._lat { + params.push(("lat", value.to_string())); + } + if let Some(value) = self._customer_phone_number { + params.push(("customerPhoneNumber", value.to_string())); + } + if let Some(value) = self._customer_name { + params.push(("customerName", value.to_string())); + } + if self._custom_field.len() > 0 { + let mut s = String::new(); + for f in self._custom_field.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("customField", s)); + } + if let Some(value) = self._assignee { + params.push(("assignee", value.to_string())); + } + if let Some(value) = self._address { + params.push(("address", value.to_string())); + } + for &field in ["alt", "teamId", "jobId", "title", "progress", "note", "lng", "lat", "customerPhoneNumber", "customerName", "customField", "assignee", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Job) -> JobPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *title* query property to the given value. + /// + /// + /// Job title + pub fn title(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._title = Some(new_value.to_string()); + self + } + /// Sets the *progress* query property to the given value. + /// + /// + /// Job progress + pub fn progress(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._progress = Some(new_value.to_string()); + self + } + /// Sets the *note* query property to the given value. + /// + /// + /// Job note as newline (Unix) separated string + pub fn note(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._note = Some(new_value.to_string()); + self + } + /// Sets the *lng* query property to the given value. + /// + /// + /// The longitude coordinate of this job's location. + pub fn lng(mut self, new_value: f64) -> JobPatchCall<'a, C, NC, A> { + self._lng = Some(new_value); + self + } + /// Sets the *lat* query property to the given value. + /// + /// + /// The latitude coordinate of this job's location. + pub fn lat(mut self, new_value: f64) -> JobPatchCall<'a, C, NC, A> { + self._lat = Some(new_value); + self + } + /// Sets the *customer phone number* query property to the given value. + /// + /// + /// Customer phone number + pub fn customer_phone_number(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._customer_phone_number = Some(new_value.to_string()); + self + } + /// Sets the *customer name* query property to the given value. + /// + /// + /// Customer name + pub fn customer_name(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._customer_name = Some(new_value.to_string()); + self + } + /// Append the given value to the *custom field* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Sets the value of custom fields. To set a custom field, pass the field id (from /team/teamId/custom_fields), a URL escaped '=' character, and the desired value as a parameter. For example, customField=12%3DAlice. Repeat the parameter for each custom field. Note that '=' cannot appear in the parameter value. Specifying an invalid, or inactive enum field will result in an error 500. + pub fn add_custom_field(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._custom_field.push(new_value.to_string()); + self + } + /// Sets the *assignee* query property to the given value. + /// + /// + /// Assignee email address, or empty string to unassign. + pub fn assignee(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._assignee = Some(new_value.to_string()); + self + } + /// Sets the *address* query property to the given value. + /// + /// + /// Job address as newline (Unix) separated string + pub fn address(mut self, new_value: &str) -> JobPatchCall<'a, C, NC, A> { + self._address = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves jobs created or modified since the given timestamp. +/// +/// A builder for the *list* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().list("teamId") +/// .page_token("dolor") +/// .min_modified_timestamp_ms("et") +/// .max_results(5) +/// .doit(); +/// # } +/// ``` +pub struct JobListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _page_token: Option, + _min_modified_timestamp_ms: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, JobListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.jobs.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._min_modified_timestamp_ms { + params.push(("minModifiedTimestampMs", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "teamId", "pageToken", "minModifiedTimestampMs", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["teamId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token + pub fn page_token(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *min modified timestamp ms* query property to the given value. + /// + /// + /// Minimum time a job was modified in milliseconds since epoch. + pub fn min_modified_timestamp_ms(mut self, new_value: &str) -> JobListCall<'a, C, NC, A> { + self._min_modified_timestamp_ms = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return in one page. + pub fn max_results(mut self, new_value: u32) -> JobListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new job. Only the state field of the job should be set. +/// +/// A builder for the *insert* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Job; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Job = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.jobs().insert(&req, "teamId", "address", 0.455185502569, 0.898789428358, "title") +/// .note("sit") +/// .customer_phone_number("vero") +/// .customer_name("diam") +/// .add_custom_field("rebum.") +/// .assignee("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct JobInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _request: Job, + _team_id: String, + _address: String, + _lat: f64, + _lng: f64, + _title: String, + _note: Option, + _customer_phone_number: Option, + _customer_name: Option, + _custom_field: Vec, + _assignee: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for JobInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> JobInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Job)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.jobs.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("address", self._address.to_string())); + params.push(("lat", self._lat.to_string())); + params.push(("lng", self._lng.to_string())); + params.push(("title", self._title.to_string())); + if let Some(value) = self._note { + params.push(("note", value.to_string())); + } + if let Some(value) = self._customer_phone_number { + params.push(("customerPhoneNumber", value.to_string())); + } + if let Some(value) = self._customer_name { + params.push(("customerName", value.to_string())); + } + if self._custom_field.len() > 0 { + let mut s = String::new(); + for f in self._custom_field.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("customField", s)); + } + if let Some(value) = self._assignee { + params.push(("assignee", value.to_string())); + } + for &field in ["alt", "teamId", "address", "lat", "lng", "title", "note", "customerPhoneNumber", "customerName", "customField", "assignee"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["teamId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Job) -> JobInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *address* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job address as newline (Unix) separated string + pub fn address(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._address = new_value.to_string(); + self + } + /// Sets the *lat* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The latitude coordinate of this job's location. + pub fn lat(mut self, new_value: f64) -> JobInsertCall<'a, C, NC, A> { + self._lat = new_value; + self + } + /// Sets the *lng* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The longitude coordinate of this job's location. + pub fn lng(mut self, new_value: f64) -> JobInsertCall<'a, C, NC, A> { + self._lng = new_value; + self + } + /// Sets the *title* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job title + pub fn title(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._title = new_value.to_string(); + self + } + /// Sets the *note* query property to the given value. + /// + /// + /// Job note as newline (Unix) separated string + pub fn note(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._note = Some(new_value.to_string()); + self + } + /// Sets the *customer phone number* query property to the given value. + /// + /// + /// Customer phone number + pub fn customer_phone_number(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._customer_phone_number = Some(new_value.to_string()); + self + } + /// Sets the *customer name* query property to the given value. + /// + /// + /// Customer name + pub fn customer_name(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._customer_name = Some(new_value.to_string()); + self + } + /// Append the given value to the *custom field* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Sets the value of custom fields. To set a custom field, pass the field id (from /team/teamId/custom_fields), a URL escaped '=' character, and the desired value as a parameter. For example, customField=12%3DAlice. Repeat the parameter for each custom field. Note that '=' cannot appear in the parameter value. Specifying an invalid, or inactive enum field will result in an error 500. + pub fn add_custom_field(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._custom_field.push(new_value.to_string()); + self + } + /// Sets the *assignee* query property to the given value. + /// + /// + /// Assignee email address, or empty string to unassign. + pub fn assignee(mut self, new_value: &str) -> JobInsertCall<'a, C, NC, A> { + self._assignee = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> JobInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Replaces the schedule of a job with the provided schedule. +/// +/// A builder for the *update* method supported by a *schedule* resource. +/// It is not used directly, but through a `ScheduleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Schedule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Schedule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schedule().update(&req, "teamId", "jobId") +/// .start_time("sadipscing") +/// .end_time("invidunt") +/// .duration("consetetur") +/// .all_day(false) +/// .doit(); +/// # } +/// ``` +pub struct ScheduleUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _request: Schedule, + _team_id: String, + _job_id: String, + _start_time: Option, + _end_time: Option, + _duration: Option, + _all_day: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ScheduleUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ScheduleUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schedule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.schedule.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + if let Some(value) = self._duration { + params.push(("duration", value.to_string())); + } + if let Some(value) = self._all_day { + params.push(("allDay", value.to_string())); + } + for &field in ["alt", "teamId", "jobId", "startTime", "endTime", "duration", "allDay"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}/schedule".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Schedule) -> ScheduleUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// Scheduled start time in milliseconds since epoch. + pub fn start_time(mut self, new_value: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// Scheduled end time in milliseconds since epoch. + pub fn end_time(mut self, new_value: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *duration* query property to the given value. + /// + /// + /// Job duration in milliseconds. + pub fn duration(mut self, new_value: &str) -> ScheduleUpdateCall<'a, C, NC, A> { + self._duration = Some(new_value.to_string()); + self + } + /// Sets the *all day* query property to the given value. + /// + /// + /// Whether the job is scheduled for the whole day. Time of day in start/end times is ignored if this is true. + pub fn all_day(mut self, new_value: bool) -> ScheduleUpdateCall<'a, C, NC, A> { + self._all_day = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ScheduleUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ScheduleUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ScheduleUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Replaces the schedule of a job with the provided schedule. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *schedule* resource. +/// It is not used directly, but through a `ScheduleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// use coordinate1::Schedule; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Schedule = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schedule().patch(&req, "teamId", "jobId") +/// .start_time("Lorem") +/// .end_time("et") +/// .duration("clita") +/// .all_day(true) +/// .doit(); +/// # } +/// ``` +pub struct SchedulePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _request: Schedule, + _team_id: String, + _job_id: String, + _start_time: Option, + _end_time: Option, + _duration: Option, + _all_day: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SchedulePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SchedulePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schedule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.schedule.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + if let Some(value) = self._duration { + params.push(("duration", value.to_string())); + } + if let Some(value) = self._all_day { + params.push(("allDay", value.to_string())); + } + for &field in ["alt", "teamId", "jobId", "startTime", "endTime", "duration", "allDay"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}/schedule".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Schedule) -> SchedulePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> SchedulePatchCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> SchedulePatchCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// Scheduled start time in milliseconds since epoch. + pub fn start_time(mut self, new_value: &str) -> SchedulePatchCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// Scheduled end time in milliseconds since epoch. + pub fn end_time(mut self, new_value: &str) -> SchedulePatchCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *duration* query property to the given value. + /// + /// + /// Job duration in milliseconds. + pub fn duration(mut self, new_value: &str) -> SchedulePatchCall<'a, C, NC, A> { + self._duration = Some(new_value.to_string()); + self + } + /// Sets the *all day* query property to the given value. + /// + /// + /// Whether the job is scheduled for the whole day. Time of day in start/end times is ignored if this is true. + pub fn all_day(mut self, new_value: bool) -> SchedulePatchCall<'a, C, NC, A> { + self._all_day = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchedulePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SchedulePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SchedulePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the schedule for a job. +/// +/// A builder for the *get* method supported by a *schedule* resource. +/// It is not used directly, but through a `ScheduleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.schedule().get("teamId", "jobId") +/// .doit(); +/// # } +/// ``` +pub struct ScheduleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _job_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ScheduleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ScheduleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Schedule)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.schedule.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("jobId", self._job_id.to_string())); + for &field in ["alt", "teamId", "jobId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/jobs/{jobId}/schedule".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{jobId}", "jobId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "jobId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> ScheduleGetCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *job id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Job number + pub fn job_id(mut self, new_value: &str) -> ScheduleGetCall<'a, C, NC, A> { + self._job_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ScheduleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ScheduleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ScheduleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of workers in a team. +/// +/// A builder for the *list* method supported by a *worker* resource. +/// It is not used directly, but through a `WorkerMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.worker().list("teamId") +/// .doit(); +/// # } +/// ``` +pub struct WorkerListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for WorkerListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> WorkerListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, WorkerListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.worker.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + for &field in ["alt", "teamId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/workers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["teamId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> WorkerListCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> WorkerListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> WorkerListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> WorkerListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of locations for a worker. +/// +/// A builder for the *list* method supported by a *location* resource. +/// It is not used directly, but through a `LocationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.location().list("teamId", "workerEmail", "startTimestampMs") +/// .page_token("labore") +/// .max_results(64) +/// .doit(); +/// # } +/// ``` +pub struct LocationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _worker_email: String, + _start_timestamp_ms: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LocationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LocationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LocationListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.location.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + params.push(("workerEmail", self._worker_email.to_string())); + params.push(("startTimestampMs", self._start_timestamp_ms.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "teamId", "workerEmail", "startTimestampMs", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/workers/{workerEmail}/locations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId"), ("{workerEmail}", "workerEmail")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["teamId", "workerEmail"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> LocationListCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *worker email* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Worker email address. + pub fn worker_email(mut self, new_value: &str) -> LocationListCall<'a, C, NC, A> { + self._worker_email = new_value.to_string(); + self + } + /// Sets the *start timestamp ms* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Start timestamp in milliseconds since the epoch. + pub fn start_timestamp_ms(mut self, new_value: &str) -> LocationListCall<'a, C, NC, A> { + self._start_timestamp_ms = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Continuation token + pub fn page_token(mut self, new_value: &str) -> LocationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return in one page. + pub fn max_results(mut self, new_value: u32) -> LocationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LocationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LocationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LocationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of teams for a user. +/// +/// A builder for the *list* method supported by a *team* resource. +/// It is not used directly, but through a `TeamMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.team().list() +/// .worker(false) +/// .dispatcher(false) +/// .admin(false) +/// .doit(); +/// # } +/// ``` +pub struct TeamListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _worker: Option, + _dispatcher: Option, + _admin: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TeamListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TeamListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TeamListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.team.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + if let Some(value) = self._worker { + params.push(("worker", value.to_string())); + } + if let Some(value) = self._dispatcher { + params.push(("dispatcher", value.to_string())); + } + if let Some(value) = self._admin { + params.push(("admin", value.to_string())); + } + for &field in ["alt", "worker", "dispatcher", "admin"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *worker* query property to the given value. + /// + /// + /// Whether to include teams for which the user has the Worker role. + pub fn worker(mut self, new_value: bool) -> TeamListCall<'a, C, NC, A> { + self._worker = Some(new_value); + self + } + /// Sets the *dispatcher* query property to the given value. + /// + /// + /// Whether to include teams for which the user has the Dispatcher role. + pub fn dispatcher(mut self, new_value: bool) -> TeamListCall<'a, C, NC, A> { + self._dispatcher = Some(new_value); + self + } + /// Sets the *admin* query property to the given value. + /// + /// + /// Whether to include teams for which the user has the Admin role. + pub fn admin(mut self, new_value: bool) -> TeamListCall<'a, C, NC, A> { + self._admin = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TeamListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TeamListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TeamListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of custom field definitions for a team. +/// +/// A builder for the *list* method supported by a *customFieldDef* resource. +/// It is not used directly, but through a `CustomFieldDefMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-coordinate1" as coordinate1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use coordinate1::Coordinate; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Coordinate::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.custom_field_def().list("teamId") +/// .doit(); +/// # } +/// ``` +pub struct CustomFieldDefListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Coordinate, + _team_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CustomFieldDefListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CustomFieldDefListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CustomFieldDefListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "coordinate.customFieldDef.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("teamId", self._team_id.to_string())); + for &field in ["alt", "teamId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/coordinate/v1/teams/{teamId}/custom_fields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{teamId}", "teamId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["teamId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *team id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Team ID + pub fn team_id(mut self, new_value: &str) -> CustomFieldDefListCall<'a, C, NC, A> { + self._team_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomFieldDefListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomFieldDefListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomFieldDefListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/customsearch1/Cargo.toml b/gen/customsearch1/Cargo.toml new file mode 100644 index 0000000000..4421729723 --- /dev/null +++ b/gen/customsearch1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-customsearch1" +version = "0.1.0+20131205" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with customsearch (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/customsearch1" +homepage = "https://developers.google.com/custom-search/v1/using_rest" +documentation = "http://byron.github.io/google-apis-rs/google-customsearch1" +license = "MIT" +keywords = ["customsearch", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/customsearch1/LICENSE.md b/gen/customsearch1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/customsearch1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/customsearch1/README.md b/gen/customsearch1/README.md new file mode 100644 index 0000000000..0ef9ae62d7 --- /dev/null +++ b/gen/customsearch1/README.md @@ -0,0 +1,194 @@ + +The `google-customsearch1` library allows access to all features of the *Google customsearch* service. + +This documentation was generated from *customsearch* crate version *0.1.0+20131205*, where *20131205* is the exact revision of the *customsearch:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *customsearch* *v1* API can be found at the +[official documentation site](https://developers.google.com/custom-search/v1/using_rest). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-customsearch1/struct.Customsearch.html) ... + +* cse + * [*list*](http://byron.github.io/google-apis-rs/google-customsearch1/struct.CseListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-customsearch1/struct.Customsearch.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-customsearch1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.cse().list(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-customsearch1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-customsearch1" as customsearch1; +use customsearch1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use customsearch1::Customsearch; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Customsearch::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.cse().list("q") + .start(53) + .sort("Stet") + .site_search_filter("sed") + .site_search("et") + .search_type("dolores") + .safe("kasd") + .rights("accusam") + .related_site("takimata") + .or_terms("justo") + .num(100) + .lr("erat") + .low_range("labore") + .link_site("sea") + .img_type("nonumy") + .img_size("dolores") + .img_dominant_color("gubergren") + .img_color_type("sadipscing") + .hq("aliquyam") + .hl("ea") + .high_range("no") + .googlehost("justo") + .gl("justo") + .filter("et") + .file_type("et") + .exclude_terms("diam") + .exact_terms("ipsum") + .date_restrict("Lorem") + .cx("et") + .cref("duo") + .cr("aliquyam") + .c2coff("sea") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-customsearch1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-customsearch1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-customsearch1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-customsearch1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-customsearch1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-customsearch1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-customsearch1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-customsearch1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-customsearch1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-customsearch1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **customsearch1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/customsearch1/src/cmn.rs b/gen/customsearch1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/customsearch1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/customsearch1/src/lib.rs b/gen/customsearch1/src/lib.rs new file mode 100644 index 0000000000..14871b2e30 --- /dev/null +++ b/gen/customsearch1/src/lib.rs @@ -0,0 +1,1437 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *customsearch* crate version *0.1.0+20131205*, where *20131205* is the exact revision of the *customsearch:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *customsearch* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/custom-search/v1/using_rest). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/customsearch1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Customsearch.html) ... +//! +//! * cse +//! * [*list*](struct.CseListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Customsearch.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.cse().list(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-customsearch1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-customsearch1" as customsearch1; +//! use customsearch1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use customsearch1::Customsearch; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Customsearch::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.cse().list("q") +//! .start(26) +//! .sort("erat") +//! .site_search_filter("sadipscing") +//! .site_search("dolor") +//! .search_type("eirmod") +//! .safe("elitr") +//! .rights("amet") +//! .related_site("no") +//! .or_terms("labore") +//! .num(62) +//! .lr("dolore") +//! .low_range("invidunt") +//! .link_site("aliquyam") +//! .img_type("accusam") +//! .img_size("Lorem") +//! .img_dominant_color("sea") +//! .img_color_type("et") +//! .hq("duo") +//! .hl("et") +//! .high_range("eirmod") +//! .googlehost("sanctus") +//! .gl("et") +//! .filter("amet") +//! .file_type("et") +//! .exclude_terms("consetetur") +//! .exact_terms("ut") +//! .date_restrict("ea") +//! .cx("sed") +//! .cref("dolor") +//! .cr("dolor") +//! .c2coff("dolor") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Customsearch related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-customsearch1" as customsearch1; +/// use customsearch1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use customsearch1::Customsearch; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Customsearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cse().list("q") +/// .start(5) +/// .sort("amet.") +/// .site_search_filter("voluptua.") +/// .site_search("Lorem") +/// .search_type("gubergren") +/// .safe("justo") +/// .rights("sit") +/// .related_site("vero") +/// .or_terms("diam") +/// .num(35) +/// .lr("consetetur") +/// .low_range("sadipscing") +/// .link_site("vero") +/// .img_type("sadipscing") +/// .img_size("invidunt") +/// .img_dominant_color("consetetur") +/// .img_color_type("dolore") +/// .hq("duo") +/// .hl("aliquyam") +/// .high_range("Lorem") +/// .googlehost("et") +/// .gl("clita") +/// .filter("consetetur") +/// .file_type("takimata") +/// .exclude_terms("nonumy") +/// .exact_terms("kasd") +/// .date_restrict("sanctus") +/// .cx("takimata") +/// .cref("At") +/// .cr("labore") +/// .c2coff("invidunt") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Customsearch { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Customsearch {} + +impl<'a, C, NC, A> Customsearch + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Customsearch { + Customsearch { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn cse(&'a self) -> CseMethods<'a, C, NC, A> { + CseMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResultImage { + /// no description provided + pub width: i32, + /// no description provided + #[serde(alias="contextLink")] + pub context_link: String, + /// no description provided + #[serde(alias="thumbnailWidth")] + pub thumbnail_width: i32, + /// no description provided + #[serde(alias="thumbnailLink")] + pub thumbnail_link: String, + /// no description provided + #[serde(alias="byteSize")] + pub byte_size: i32, + /// no description provided + #[serde(alias="thumbnailHeight")] + pub thumbnail_height: i32, + /// no description provided + pub height: i32, +} + +impl NestedType for ResultImage {} +impl Part for ResultImage {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list cse](struct.CseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Search { + /// no description provided + pub promotions: Vec, + /// no description provided + pub kind: String, + /// no description provided + pub url: SearchUrl, + /// no description provided + pub items: Vec, + /// no description provided + pub context: Context, + /// no description provided + pub queries: HashMap>, + /// no description provided + pub spelling: SearchSpelling, + /// no description provided + #[serde(alias="searchInformation")] + pub search_information: SearchSearchInformation, +} + +impl ResponseResult for Search {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PromotionImage { + /// no description provided + pub source: String, + /// no description provided + pub height: i32, + /// no description provided + pub width: i32, +} + +impl NestedType for PromotionImage {} +impl Part for PromotionImage {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SearchUrl { + /// no description provided + #[serde(alias="type")] + pub type_: String, + /// no description provided + pub template: String, +} + +impl NestedType for SearchUrl {} +impl Part for SearchUrl {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SearchSpelling { + /// no description provided + #[serde(alias="correctedQuery")] + pub corrected_query: String, + /// no description provided + #[serde(alias="htmlCorrectedQuery")] + pub html_corrected_query: String, +} + +impl NestedType for SearchSpelling {} +impl Part for SearchSpelling {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PromotionBodyLines { + /// no description provided + pub url: String, + /// no description provided + #[serde(alias="htmlTitle")] + pub html_title: String, + /// no description provided + pub link: String, + /// no description provided + pub title: String, +} + +impl NestedType for PromotionBodyLines {} +impl Part for PromotionBodyLines {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResultType { + /// no description provided + pub kind: String, + /// no description provided + pub labels: Vec, + /// no description provided + pub title: String, + /// no description provided + #[serde(alias="displayLink")] + pub display_link: String, + /// no description provided + #[serde(alias="cacheId")] + pub cache_id: String, + /// no description provided + #[serde(alias="formattedUrl")] + pub formatted_url: String, + /// no description provided + #[serde(alias="htmlFormattedUrl")] + pub html_formatted_url: String, + /// no description provided + pub pagemap: HashMap>>, + /// no description provided + #[serde(alias="fileFormat")] + pub file_format: String, + /// no description provided + pub snippet: String, + /// no description provided + #[serde(alias="htmlSnippet")] + pub html_snippet: String, + /// no description provided + pub link: String, + /// no description provided + pub image: ResultImage, + /// no description provided + pub mime: String, + /// no description provided + #[serde(alias="htmlTitle")] + pub html_title: String, +} + +impl Part for ResultType {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Context { + /// no description provided + pub facets: Vec>, + /// no description provided + pub title: String, +} + +impl Part for Context {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ContextFacets { + /// no description provided + pub label_with_op: String, + /// no description provided + pub anchor: String, + /// no description provided + pub label: String, +} + +impl NestedType for ContextFacets {} +impl Part for ContextFacets {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Query { + /// no description provided + #[serde(alias="dateRestrict")] + pub date_restrict: String, + /// no description provided + #[serde(alias="inputEncoding")] + pub input_encoding: String, + /// no description provided + #[serde(alias="orTerms")] + pub or_terms: String, + /// no description provided + #[serde(alias="highRange")] + pub high_range: String, + /// no description provided + pub cx: String, + /// no description provided + #[serde(alias="startPage")] + pub start_page: i32, + /// no description provided + #[serde(alias="disableCnTwTranslation")] + pub disable_cn_tw_translation: String, + /// no description provided + pub cr: String, + /// no description provided + #[serde(alias="imgType")] + pub img_type: String, + /// no description provided + #[serde(alias="relatedSite")] + pub related_site: String, + /// no description provided + pub gl: String, + /// no description provided + #[serde(alias="searchType")] + pub search_type: String, + /// no description provided + pub title: String, + /// no description provided + #[serde(alias="googleHost")] + pub google_host: String, + /// no description provided + #[serde(alias="fileType")] + pub file_type: String, + /// no description provided + #[serde(alias="imgDominantColor")] + pub img_dominant_color: String, + /// no description provided + #[serde(alias="siteSearch")] + pub site_search: String, + /// no description provided + pub cref: String, + /// no description provided + pub sort: String, + /// no description provided + pub hq: String, + /// no description provided + #[serde(alias="outputEncoding")] + pub output_encoding: String, + /// no description provided + pub safe: String, + /// no description provided + #[serde(alias="searchTerms")] + pub search_terms: String, + /// no description provided + #[serde(alias="exactTerms")] + pub exact_terms: String, + /// no description provided + #[serde(alias="imgColorType")] + pub img_color_type: String, + /// no description provided + pub hl: String, + /// no description provided + #[serde(alias="totalResults")] + pub total_results: String, + /// no description provided + #[serde(alias="lowRange")] + pub low_range: String, + /// no description provided + pub count: i32, + /// no description provided + #[serde(alias="imgSize")] + pub img_size: String, + /// no description provided + pub language: String, + /// no description provided + pub rights: String, + /// no description provided + #[serde(alias="startIndex")] + pub start_index: i32, + /// no description provided + #[serde(alias="excludeTerms")] + pub exclude_terms: String, + /// no description provided + pub filter: String, + /// no description provided + #[serde(alias="linkSite")] + pub link_site: String, + /// no description provided + #[serde(alias="siteSearchFilter")] + pub site_search_filter: String, +} + +impl Part for Query {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Promotion { + /// no description provided + #[serde(alias="bodyLines")] + pub body_lines: Vec, + /// no description provided + pub title: String, + /// no description provided + pub link: String, + /// no description provided + #[serde(alias="displayLink")] + pub display_link: String, + /// no description provided + #[serde(alias="htmlTitle")] + pub html_title: String, + /// no description provided + pub image: PromotionImage, +} + +impl Part for Promotion {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SearchSearchInformation { + /// no description provided + #[serde(alias="formattedSearchTime")] + pub formatted_search_time: String, + /// no description provided + #[serde(alias="formattedTotalResults")] + pub formatted_total_results: String, + /// no description provided + #[serde(alias="totalResults")] + pub total_results: String, + /// no description provided + #[serde(alias="searchTime")] + pub search_time: f64, +} + +impl NestedType for SearchSearchInformation {} +impl Part for SearchSearchInformation {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResultLabels { + /// no description provided + #[serde(alias="displayName")] + pub display_name: String, + /// no description provided + pub label_with_op: String, + /// no description provided + pub name: String, +} + +impl NestedType for ResultLabels {} +impl Part for ResultLabels {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *cse* resources. +/// It is not used directly, but through the `Customsearch` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-customsearch1" as customsearch1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use customsearch1::Customsearch; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Customsearch::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.cse(); +/// # } +/// ``` +pub struct CseMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Customsearch, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CseMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CseMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results. + pub fn list(&self, q: &str) -> CseListCall<'a, C, NC, A> { + CseListCall { + hub: self.hub, + _q: q.to_string(), + _start: Default::default(), + _sort: Default::default(), + _site_search_filter: Default::default(), + _site_search: Default::default(), + _search_type: Default::default(), + _safe: Default::default(), + _rights: Default::default(), + _related_site: Default::default(), + _or_terms: Default::default(), + _num: Default::default(), + _lr: Default::default(), + _low_range: Default::default(), + _link_site: Default::default(), + _img_type: Default::default(), + _img_size: Default::default(), + _img_dominant_color: Default::default(), + _img_color_type: Default::default(), + _hq: Default::default(), + _hl: Default::default(), + _high_range: Default::default(), + _googlehost: Default::default(), + _gl: Default::default(), + _filter: Default::default(), + _file_type: Default::default(), + _exclude_terms: Default::default(), + _exact_terms: Default::default(), + _date_restrict: Default::default(), + _cx: Default::default(), + _cref: Default::default(), + _cr: Default::default(), + _c2coff: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results. +/// +/// A builder for the *list* method supported by a *cse* resource. +/// It is not used directly, but through a `CseMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-customsearch1" as customsearch1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use customsearch1::Customsearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Customsearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cse().list("q") +/// .start(6) +/// .sort("rebum.") +/// .site_search_filter("dolore") +/// .site_search("nonumy") +/// .search_type("sed") +/// .safe("aliquyam") +/// .rights("sit") +/// .related_site("eirmod") +/// .or_terms("consetetur") +/// .num(16) +/// .lr("sed") +/// .low_range("ea") +/// .link_site("gubergren") +/// .img_type("aliquyam") +/// .img_size("eos") +/// .img_dominant_color("tempor") +/// .img_color_type("sea") +/// .hq("labore") +/// .hl("ipsum") +/// .high_range("aliquyam") +/// .googlehost("dolores") +/// .gl("sit") +/// .filter("diam") +/// .file_type("ut") +/// .exclude_terms("justo") +/// .exact_terms("est") +/// .date_restrict("amet") +/// .cx("accusam") +/// .cref("clita") +/// .cr("diam") +/// .c2coff("justo") +/// .doit(); +/// # } +/// ``` +pub struct CseListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Customsearch, + _q: String, + _start: Option, + _sort: Option, + _site_search_filter: Option, + _site_search: Option, + _search_type: Option, + _safe: Option, + _rights: Option, + _related_site: Option, + _or_terms: Option, + _num: Option, + _lr: Option, + _low_range: Option, + _link_site: Option, + _img_type: Option, + _img_size: Option, + _img_dominant_color: Option, + _img_color_type: Option, + _hq: Option, + _hl: Option, + _high_range: Option, + _googlehost: Option, + _gl: Option, + _filter: Option, + _file_type: Option, + _exclude_terms: Option, + _exact_terms: Option, + _date_restrict: Option, + _cx: Option, + _cref: Option, + _cr: Option, + _c2coff: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for CseListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CseListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Search)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "search.cse.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((34 + self._additional_params.len())); + params.push(("q", self._q.to_string())); + if let Some(value) = self._start { + params.push(("start", value.to_string())); + } + if let Some(value) = self._sort { + params.push(("sort", value.to_string())); + } + if let Some(value) = self._site_search_filter { + params.push(("siteSearchFilter", value.to_string())); + } + if let Some(value) = self._site_search { + params.push(("siteSearch", value.to_string())); + } + if let Some(value) = self._search_type { + params.push(("searchType", value.to_string())); + } + if let Some(value) = self._safe { + params.push(("safe", value.to_string())); + } + if let Some(value) = self._rights { + params.push(("rights", value.to_string())); + } + if let Some(value) = self._related_site { + params.push(("relatedSite", value.to_string())); + } + if let Some(value) = self._or_terms { + params.push(("orTerms", value.to_string())); + } + if let Some(value) = self._num { + params.push(("num", value.to_string())); + } + if let Some(value) = self._lr { + params.push(("lr", value.to_string())); + } + if let Some(value) = self._low_range { + params.push(("lowRange", value.to_string())); + } + if let Some(value) = self._link_site { + params.push(("linkSite", value.to_string())); + } + if let Some(value) = self._img_type { + params.push(("imgType", value.to_string())); + } + if let Some(value) = self._img_size { + params.push(("imgSize", value.to_string())); + } + if let Some(value) = self._img_dominant_color { + params.push(("imgDominantColor", value.to_string())); + } + if let Some(value) = self._img_color_type { + params.push(("imgColorType", value.to_string())); + } + if let Some(value) = self._hq { + params.push(("hq", value.to_string())); + } + if let Some(value) = self._hl { + params.push(("hl", value.to_string())); + } + if let Some(value) = self._high_range { + params.push(("highRange", value.to_string())); + } + if let Some(value) = self._googlehost { + params.push(("googlehost", value.to_string())); + } + if let Some(value) = self._gl { + params.push(("gl", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + if let Some(value) = self._file_type { + params.push(("fileType", value.to_string())); + } + if let Some(value) = self._exclude_terms { + params.push(("excludeTerms", value.to_string())); + } + if let Some(value) = self._exact_terms { + params.push(("exactTerms", value.to_string())); + } + if let Some(value) = self._date_restrict { + params.push(("dateRestrict", value.to_string())); + } + if let Some(value) = self._cx { + params.push(("cx", value.to_string())); + } + if let Some(value) = self._cref { + params.push(("cref", value.to_string())); + } + if let Some(value) = self._cr { + params.push(("cr", value.to_string())); + } + if let Some(value) = self._c2coff { + params.push(("c2coff", value.to_string())); + } + for &field in ["alt", "q", "start", "sort", "siteSearchFilter", "siteSearch", "searchType", "safe", "rights", "relatedSite", "orTerms", "num", "lr", "lowRange", "linkSite", "imgType", "imgSize", "imgDominantColor", "imgColorType", "hq", "hl", "highRange", "googlehost", "gl", "filter", "fileType", "excludeTerms", "exactTerms", "dateRestrict", "cx", "cref", "cr", "c2coff"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/customsearch/v1".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *q* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query + pub fn q(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._q = new_value.to_string(); + self + } + /// Sets the *start* query property to the given value. + /// + /// + /// The index of the first result to return + pub fn start(mut self, new_value: u32) -> CseListCall<'a, C, NC, A> { + self._start = Some(new_value); + self + } + /// Sets the *sort* query property to the given value. + /// + /// + /// The sort expression to apply to the results + pub fn sort(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._sort = Some(new_value.to_string()); + self + } + /// Sets the *site search filter* query property to the given value. + /// + /// + /// Controls whether to include or exclude results from the site named in the as_sitesearch parameter + pub fn site_search_filter(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._site_search_filter = Some(new_value.to_string()); + self + } + /// Sets the *site search* query property to the given value. + /// + /// + /// Specifies all search results should be pages from a given site + pub fn site_search(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._site_search = Some(new_value.to_string()); + self + } + /// Sets the *search type* query property to the given value. + /// + /// + /// Specifies the search type: image. + pub fn search_type(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._search_type = Some(new_value.to_string()); + self + } + /// Sets the *safe* query property to the given value. + /// + /// + /// Search safety level + pub fn safe(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._safe = Some(new_value.to_string()); + self + } + /// Sets the *rights* query property to the given value. + /// + /// + /// Filters based on licensing. Supported values include: cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived and combinations of these. + pub fn rights(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._rights = Some(new_value.to_string()); + self + } + /// Sets the *related site* query property to the given value. + /// + /// + /// Specifies that all search results should be pages that are related to the specified URL + pub fn related_site(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._related_site = Some(new_value.to_string()); + self + } + /// Sets the *or terms* query property to the given value. + /// + /// + /// Provides additional search terms to check for in a document, where each document in the search results must contain at least one of the additional search terms + pub fn or_terms(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._or_terms = Some(new_value.to_string()); + self + } + /// Sets the *num* query property to the given value. + /// + /// + /// Number of search results to return + pub fn num(mut self, new_value: u32) -> CseListCall<'a, C, NC, A> { + self._num = Some(new_value); + self + } + /// Sets the *lr* query property to the given value. + /// + /// + /// The language restriction for the search results + pub fn lr(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._lr = Some(new_value.to_string()); + self + } + /// Sets the *low range* query property to the given value. + /// + /// + /// Creates a range in form as_nlo value..as_nhi value and attempts to append it to query + pub fn low_range(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._low_range = Some(new_value.to_string()); + self + } + /// Sets the *link site* query property to the given value. + /// + /// + /// Specifies that all search results should contain a link to a particular URL + pub fn link_site(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._link_site = Some(new_value.to_string()); + self + } + /// Sets the *img type* query property to the given value. + /// + /// + /// Returns images of a type, which can be one of: clipart, face, lineart, news, and photo. + pub fn img_type(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._img_type = Some(new_value.to_string()); + self + } + /// Sets the *img size* query property to the given value. + /// + /// + /// Returns images of a specified size, where size can be one of: icon, small, medium, large, xlarge, xxlarge, and huge. + pub fn img_size(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._img_size = Some(new_value.to_string()); + self + } + /// Sets the *img dominant color* query property to the given value. + /// + /// + /// Returns images of a specific dominant color: yellow, green, teal, blue, purple, pink, white, gray, black and brown. + pub fn img_dominant_color(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._img_dominant_color = Some(new_value.to_string()); + self + } + /// Sets the *img color type* query property to the given value. + /// + /// + /// Returns black and white, grayscale, or color images: mono, gray, and color. + pub fn img_color_type(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._img_color_type = Some(new_value.to_string()); + self + } + /// Sets the *hq* query property to the given value. + /// + /// + /// Appends the extra query terms to the query. + pub fn hq(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._hq = Some(new_value.to_string()); + self + } + /// Sets the *hl* query property to the given value. + /// + /// + /// Sets the user interface language. + pub fn hl(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._hl = Some(new_value.to_string()); + self + } + /// Sets the *high range* query property to the given value. + /// + /// + /// Creates a range in form as_nlo value..as_nhi value and attempts to append it to query + pub fn high_range(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._high_range = Some(new_value.to_string()); + self + } + /// Sets the *googlehost* query property to the given value. + /// + /// + /// The local Google domain to use to perform the search. + pub fn googlehost(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._googlehost = Some(new_value.to_string()); + self + } + /// Sets the *gl* query property to the given value. + /// + /// + /// Geolocation of end user. + pub fn gl(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._gl = Some(new_value.to_string()); + self + } + /// Sets the *filter* query property to the given value. + /// + /// + /// Controls turning on or off the duplicate content filter. + pub fn filter(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Sets the *file type* query property to the given value. + /// + /// + /// Returns images of a specified type. Some of the allowed values are: bmp, gif, png, jpg, svg, pdf, ... + pub fn file_type(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._file_type = Some(new_value.to_string()); + self + } + /// Sets the *exclude terms* query property to the given value. + /// + /// + /// Identifies a word or phrase that should not appear in any documents in the search results + pub fn exclude_terms(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._exclude_terms = Some(new_value.to_string()); + self + } + /// Sets the *exact terms* query property to the given value. + /// + /// + /// Identifies a phrase that all documents in the search results must contain + pub fn exact_terms(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._exact_terms = Some(new_value.to_string()); + self + } + /// Sets the *date restrict* query property to the given value. + /// + /// + /// Specifies all search results are from a time period + pub fn date_restrict(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._date_restrict = Some(new_value.to_string()); + self + } + /// Sets the *cx* query property to the given value. + /// + /// + /// The custom search engine ID to scope this search query + pub fn cx(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._cx = Some(new_value.to_string()); + self + } + /// Sets the *cref* query property to the given value. + /// + /// + /// The URL of a linked custom search engine + pub fn cref(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._cref = Some(new_value.to_string()); + self + } + /// Sets the *cr* query property to the given value. + /// + /// + /// Country restrict(s). + pub fn cr(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._cr = Some(new_value.to_string()); + self + } + /// Sets the *c2coff* query property to the given value. + /// + /// + /// Turns off the translation between zh-CN and zh-TW. + pub fn c2coff(mut self, new_value: &str) -> CseListCall<'a, C, NC, A> { + self._c2coff = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CseListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CseListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + diff --git a/gen/dataflow1_b4/Cargo.toml b/gen/dataflow1_b4/Cargo.toml new file mode 100644 index 0000000000..50d451700f --- /dev/null +++ b/gen/dataflow1_b4/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-dataflow1_b4" +version = "0.1.0+20150130" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with dataflow (protocol v1b4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dataflow1_b4" +homepage = "" +documentation = "http://byron.github.io/google-apis-rs/google-dataflow1_b4" +license = "MIT" +keywords = ["dataflow", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/dataflow1_b4/LICENSE.md b/gen/dataflow1_b4/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/dataflow1_b4/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/dataflow1_b4/README.md b/gen/dataflow1_b4/README.md new file mode 100644 index 0000000000..30cc72863b --- /dev/null +++ b/gen/dataflow1_b4/README.md @@ -0,0 +1,137 @@ + +The `google-dataflow1_b4` library allows access to all features of the *Google dataflow* service. + +This documentation was generated from *dataflow* crate version *0.1.0+20150130*, where *20150130* is the exact revision of the *dataflow:v1b4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +# Features + +It seems there is nothing you can do here ... . + + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-dataflow1_b4/struct.Dataflow.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-dataflow1_b4 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-dataflow1_b4" as dataflow1_b4; + +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use dataflow1_b4::Dataflow; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Dataflow::new(hyper::Client::new(), auth); + +``` + +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-dataflow1_b4/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-dataflow1_b4/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-dataflow1_b4/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-dataflow1_b4/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **dataflow1_b4** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/dataflow1_b4/src/cmn.rs b/gen/dataflow1_b4/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/dataflow1_b4/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/dataflow1_b4/src/lib.rs b/gen/dataflow1_b4/src/lib.rs new file mode 100644 index 0000000000..c8cde20100 --- /dev/null +++ b/gen/dataflow1_b4/src/lib.rs @@ -0,0 +1,254 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *dataflow* crate version *0.1.0+20150130*, where *20150130* is the exact revision of the *dataflow:v1b4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/dataflow1_b4). +//! # Features +//! +//! It seems there is nothing you can do here ... . +//! +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Dataflow.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-dataflow1_b4 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-dataflow1_b4" as dataflow1_b4; +//! +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use dataflow1_b4::Dataflow; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Dataflow::new(hyper::Client::new(), auth); +//! # } +//! ``` +//! +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Dataflow related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dataflow1_b4" as dataflow1_b4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dataflow1_b4::Dataflow; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dataflow::new(hyper::Client::new(), auth); +/// # } +/// ``` +/// +pub struct Dataflow { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Dataflow {} + +impl<'a, C, NC, A> Dataflow + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Dataflow { + Dataflow { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + + +// ################### +// MethodBuilders ### +// ################# + + + +// ################### +// CallBuilders ### +// ################# + diff --git a/gen/datastore1_beta2/Cargo.toml b/gen/datastore1_beta2/Cargo.toml new file mode 100644 index 0000000000..1e5442de45 --- /dev/null +++ b/gen/datastore1_beta2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-datastore1_beta2" +version = "0.1.0+20140916" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with datastore (protocol v1beta2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1_beta2" +homepage = "https://developers.google.com/datastore/" +documentation = "http://byron.github.io/google-apis-rs/google-datastore1_beta2" +license = "MIT" +keywords = ["datastore", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/datastore1_beta2/LICENSE.md b/gen/datastore1_beta2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/datastore1_beta2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/datastore1_beta2/README.md b/gen/datastore1_beta2/README.md new file mode 100644 index 0000000000..c5207c7369 --- /dev/null +++ b/gen/datastore1_beta2/README.md @@ -0,0 +1,169 @@ + +The `google-datastore1_beta2` library allows access to all features of the *Google datastore* service. + +This documentation was generated from *datastore* crate version *0.1.0+20140916*, where *20140916* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *datastore* *v1_beta2* API can be found at the +[official documentation site](https://developers.google.com/datastore/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.Datastore.html) ... + +* datasets + * [*allocate ids*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetAllocateIdCall.html), [*begin transaction*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetBeginTransactionCall.html), [*commit*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetCommitCall.html), [*lookup*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetLookupCall.html), [*rollback*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetRollbackCall.html) and [*run query*](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.DatasetRunQueryCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-datastore1_beta2/struct.Datastore.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.datasets().lookup(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-datastore1_beta2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-datastore1_beta2" as datastore1_beta2; +use datastore1_beta2::LookupRequest; +use datastore1_beta2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use datastore1_beta2::Datastore; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Datastore::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: LookupRequest = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.datasets().lookup(&req, "datasetId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-datastore1_beta2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-datastore1_beta2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-datastore1_beta2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-datastore1_beta2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **datastore1_beta2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/datastore1_beta2/src/cmn.rs b/gen/datastore1_beta2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/datastore1_beta2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/datastore1_beta2/src/lib.rs b/gen/datastore1_beta2/src/lib.rs new file mode 100644 index 0000000000..3ec53b5908 --- /dev/null +++ b/gen/datastore1_beta2/src/lib.rs @@ -0,0 +1,2707 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *datastore* crate version *0.1.0+20140916*, where *20140916* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *datastore* *v1_beta2* API can be found at the +//! [official documentation site](https://developers.google.com/datastore/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/datastore1_beta2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Datastore.html) ... +//! +//! * datasets +//! * [*allocate ids*](struct.DatasetAllocateIdCall.html), [*begin transaction*](struct.DatasetBeginTransactionCall.html), [*commit*](struct.DatasetCommitCall.html), [*lookup*](struct.DatasetLookupCall.html), [*rollback*](struct.DatasetRollbackCall.html) and [*run query*](struct.DatasetRunQueryCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Datastore.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.datasets().lookup(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-datastore1_beta2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-datastore1_beta2" as datastore1_beta2; +//! use datastore1_beta2::LookupRequest; +//! use datastore1_beta2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use datastore1_beta2::Datastore; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Datastore::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: LookupRequest = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.datasets().lookup(&req, "datasetId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your email address + UserinfoEmail, + + /// View and manage your Google Cloud Datastore data + Full, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::UserinfoEmail => "https://www.googleapis.com/auth/userinfo.email", + Scope::Full => "https://www.googleapis.com/auth/datastore", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Datastore related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::LookupRequest; +/// use datastore1_beta2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use datastore1_beta2::Datastore; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: LookupRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().lookup(&req, "datasetId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Datastore { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Datastore {} + +impl<'a, C, NC, A> Datastore + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Datastore { + Datastore { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn datasets(&'a self) -> DatasetMethods<'a, C, NC, A> { + DatasetMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// An identifier for a particular subset of entities. +/// +/// Entities are partitioned into various subsets, each used by different datasets and different namespaces within a dataset and so forth. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PartitionId { + /// The namespace. + pub namespace: String, + /// The dataset ID. + #[serde(alias="datasetId")] + pub dataset_id: String, +} + +impl Part for PartitionId {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [allocate ids datasets](struct.DatasetAllocateIdCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AllocateIdsResponse { + /// The keys specified in the request (in the same order), each with its key path completed with a newly allocated ID. + pub keys: Vec, + /// no description provided + pub header: ResponseHeader, +} + +impl ResponseResult for AllocateIdsResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [lookup datasets](struct.DatasetLookupCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct LookupRequest { + /// Keys of entities to look up from the datastore. + pub keys: Option>, + /// Options for this lookup request. Optional. + #[serde(alias="readOptions")] + pub read_options: Option, +} + +impl RequestValue for LookupRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [begin transaction datasets](struct.DatasetBeginTransactionCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BeginTransactionResponse { + /// no description provided + pub header: ResponseHeader, + /// The transaction identifier (always present). + pub transaction: String, +} + +impl ResponseResult for BeginTransactionResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [allocate ids datasets](struct.DatasetAllocateIdCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct AllocateIdsRequest { + /// A list of keys with incomplete key paths to allocate IDs for. No key may be reserved/read-only. + pub keys: Option>, +} + +impl RequestValue for AllocateIdsRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [run query datasets](struct.DatasetRunQueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RunQueryResponse { + /// no description provided + pub header: ResponseHeader, + /// A batch of query results (always present). + pub batch: QueryResultBatch, +} + +impl ResponseResult for RunQueryResponse {} + + +/// A set of changes to apply. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct Mutation { + /// Entities to insert. Each inserted entity's key must have a complete path and must not be reserved/read-only. + pub insert: Vec, + /// Ignore a user specified read-only period. Optional. + pub force: bool, + /// Insert entities with a newly allocated ID. Each inserted entity's key must omit the final identifier in its path and must not be reserved/read-only. + #[serde(alias="insertAutoId")] + pub insert_auto_id: Vec, + /// Keys of entities to delete. Each key must have a complete key path and must not be reserved/read-only. + pub delete: Vec, + /// Entities to update. Each updated entity's key must have a complete path and must not be reserved/read-only. + pub update: Vec, + /// Entities to upsert. Each upserted entity's key must have a complete path and must not be reserved/read-only. + pub upsert: Vec, +} + +impl Part for Mutation {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [commit datasets](struct.DatasetCommitCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CommitResponse { + /// no description provided + pub header: ResponseHeader, + /// The result of performing the mutation (if any). + #[serde(alias="mutationResult")] + pub mutation_result: MutationResult, +} + +impl ResponseResult for CommitResponse {} + + +/// A batch of results produced by a query. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct QueryResultBatch { + /// The state of the query after the current batch. One of notFinished, moreResultsAfterLimit, noMoreResults. + #[serde(alias="moreResults")] + pub more_results: String, + /// The number of results skipped because of Query.offset. + #[serde(alias="skippedResults")] + pub skipped_results: i32, + /// A cursor that points to the position after the last result in the batch. May be absent. TODO(arfuller): Once all plans produce cursors update documentation here. + #[serde(alias="endCursor")] + pub end_cursor: String, + /// The results for this batch. + #[serde(alias="entityResults")] + pub entity_results: Vec, + /// The result type for every entity in entityResults. full for full entities, projection for entities with only projected properties, keyOnly for entities with only a key. + #[serde(alias="entityResultType")] + pub entity_result_type: String, +} + +impl Part for QueryResultBatch {} + + +/// A reference to a property relative to the kind expressions. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct PropertyReference { + /// The name of the property. + pub name: String, +} + +impl Part for PropertyReference {} + + +/// The result of fetching an entity from the datastore. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EntityResult { + /// The resulting entity. + pub entity: Entity, +} + +impl Part for EntityResult {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [rollback datasets](struct.DatasetRollbackCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RollbackResponse { + /// no description provided + pub header: ResponseHeader, +} + +impl ResponseResult for RollbackResponse {} + + +/// A GQL query. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct GqlQuery { + /// When false, the query string must not contain a literal. + #[serde(alias="allowLiteral")] + pub allow_literal: bool, + /// A named argument must set field GqlQueryArg.name. No two named arguments may have the same name. For each non-reserved named binding site in the query string, there must be a named argument with that name, but not necessarily the inverse. + #[serde(alias="nameArgs")] + pub name_args: Vec, + /// The query string. + #[serde(alias="queryString")] + pub query_string: String, + /// Numbered binding site @1 references the first numbered argument, effectively using 1-based indexing, rather than the usual 0. A numbered argument must NOT set field GqlQueryArg.name. For each binding site numbered i in query_string, there must be an ith numbered argument. The inverse must also be true. + #[serde(alias="numberArgs")] + pub number_args: Vec, +} + +impl Part for GqlQuery {} + + +/// A unique identifier for an entity. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Key { + /// The entity path. An entity path consists of one or more elements composed of a kind and a string or numerical identifier, which identify entities. The first element identifies a root entity, the second element identifies a child of the root entity, the third element a child of the second entity, and so forth. The entities identified by all prefixes of the path are called the element's ancestors. An entity path is always fully complete: ALL of the entity's ancestors are required to be in the path along with the entity identifier itself. The only exception is that in some documented cases, the identifier in the last path element (for the entity) itself may be omitted. A path can never be empty. The path can have at most 100 elements. + pub path: Vec, + /// Entities are partitioned into subsets, currently identified by a dataset (usually implicitly specified by the project) and namespace ID. Queries are scoped to a single partition. + #[serde(alias="partitionId")] + pub partition_id: PartitionId, +} + +impl Part for Key {} + + +/// A representation of a property in a projection. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct PropertyExpression { + /// The aggregation function to apply to the property. Optional. Can only be used when grouping by at least one property. Must then be set on all properties in the projection that are not being grouped by. Aggregation functions: first selects the first result as determined by the query's order. + #[serde(alias="aggregationFunction")] + pub aggregation_function: String, + /// The property to project. + pub property: PropertyReference, +} + +impl Part for PropertyExpression {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MutationResult { + /// Keys for insertAutoId entities. One per entity from the request, in the same order. + #[serde(alias="insertAutoIdKeys")] + pub insert_auto_id_keys: Vec, + /// Number of index writes. + #[serde(alias="indexUpdates")] + pub index_updates: i32, +} + +impl Part for MutationResult {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct ReadOptions { + /// The transaction to use. Optional. + pub transaction: String, + /// The read consistency to use. One of default, strong, or eventual. Cannot be set when transaction is set. Lookup and ancestor queries default to strong, global queries default to eventual and cannot be set to strong. Optional. Default is default. + #[serde(alias="readConsistency")] + pub read_consistency: String, +} + +impl Part for ReadOptions {} + + +/// A filter on a specific property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct PropertyFilter { + /// The operator to filter by. One of lessThan, lessThanOrEqual, greaterThan, greaterThanOrEqual, equal, or hasAncestor. + pub operator: String, + /// The property to filter by. + pub property: PropertyReference, + /// The value to compare the property to. + pub value: Value, +} + +impl Part for PropertyFilter {} + + +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResponseHeader { + /// Identifies what kind of resource this is. Value: the fixed string "datastore#responseHeader". + pub kind: String, +} + +impl Part for ResponseHeader {} + + +/// A message that can hold any of the supported value types and associated metadata. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Value { + /// An entity value. May have no key. May have a key with an incomplete key path. May have a reserved/read-only key. + #[serde(alias="entityValue")] + pub entity_value: Entity, + /// A double value. + #[serde(alias="doubleValue")] + pub double_value: f64, + /// A blob key value. + #[serde(alias="blobKeyValue")] + pub blob_key_value: String, + /// The meaning field is reserved and should not be used. + pub meaning: i32, + /// A timestamp value. + #[serde(alias="dateTimeValue")] + pub date_time_value: String, + /// A key value. + #[serde(alias="keyValue")] + pub key_value: Key, + /// A blob value. May be a maximum of 1,000,000 bytes. + #[serde(alias="blobValue")] + pub blob_value: String, + /// If the value should be indexed. + /// + /// The indexed property may be set for a null value. When indexed is true, stringValue is limited to 500 characters and the blob value is limited to 500 bytes. Input values by default have indexed set to true; however, you can explicitly set indexed to true if you want. (An output value never has indexed explicitly set to true.) If a value is itself an entity, it cannot have indexed set to true. + pub indexed: bool, + /// A UTF-8 encoded string value. + #[serde(alias="stringValue")] + pub string_value: String, + /// A list value. Cannot contain another list value. Cannot also have a meaning and indexing set. + #[serde(alias="listValue")] + pub list_value: Vec, + /// A boolean value. + #[serde(alias="booleanValue")] + pub boolean_value: bool, + /// An integer value. + #[serde(alias="integerValue")] + pub integer_value: String, +} + +impl Part for Value {} + + +/// A holder for any type of filter. Exactly one field should be specified. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct Filter { + /// A composite filter. + #[serde(alias="compositeFilter")] + pub composite_filter: CompositeFilter, + /// A filter on a property. + #[serde(alias="propertyFilter")] + pub property_filter: PropertyFilter, +} + +impl Part for Filter {} + + +/// A (kind, ID/name) pair used to construct a key path. +/// +/// At most one of name or ID may be set. If either is set, the element is complete. If neither is set, the element is incomplete. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct KeyPathElement { + /// The kind of the entity. A kind matching regex "__.*__" is reserved/read-only. A kind must not contain more than 500 characters. Cannot be "". + pub kind: String, + /// The ID of the entity. Never equal to zero. Values less than zero are discouraged and will not be supported in the future. + pub id: String, + /// The name of the entity. A name matching regex "__.*__" is reserved/read-only. A name must not be more than 500 characters. Cannot be "". + pub name: String, +} + +impl Part for KeyPathElement {} + + +/// An entity property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Property { + /// An entity value. May have no key. May have a key with an incomplete key path. May have a reserved/read-only key. + #[serde(alias="entityValue")] + pub entity_value: Entity, + /// A double value. + #[serde(alias="doubleValue")] + pub double_value: f64, + /// A blob key value. + #[serde(alias="blobKeyValue")] + pub blob_key_value: String, + /// The meaning field is reserved and should not be used. + pub meaning: i32, + /// A timestamp value. + #[serde(alias="dateTimeValue")] + pub date_time_value: String, + /// A key value. + #[serde(alias="keyValue")] + pub key_value: Key, + /// A blob value. May be a maximum of 1,000,000 bytes. + #[serde(alias="blobValue")] + pub blob_value: String, + /// If the value should be indexed. + /// + /// The indexed property may be set for a null value. When indexed is true, stringValue is limited to 500 characters and the blob value is limited to 500 bytes. Input values by default have indexed set to true; however, you can explicitly set indexed to true if you want. (An output value never has indexed explicitly set to true.) If a value is itself an entity, it cannot have indexed set to true. + pub indexed: bool, + /// A UTF-8 encoded string value. + #[serde(alias="stringValue")] + pub string_value: String, + /// A list value. Cannot contain another list value. Cannot also have a meaning and indexing set. + #[serde(alias="listValue")] + pub list_value: Vec, + /// A boolean value. + #[serde(alias="booleanValue")] + pub boolean_value: bool, + /// An integer value. + #[serde(alias="integerValue")] + pub integer_value: String, +} + +impl Part for Property {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [lookup datasets](struct.DatasetLookupCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct LookupResponse { + /// Entities found. + pub found: Vec, + /// no description provided + pub header: ResponseHeader, + /// A list of keys that were not looked up due to resource constraints. + pub deferred: Vec, + /// Entities not found, with only the key populated. + pub missing: Vec, +} + +impl ResponseResult for LookupResponse {} + + +/// A filter that merges the multiple other filters using the given operation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct CompositeFilter { + /// The operator for combining multiple filters. Only "and" is currently supported. + pub operator: String, + /// The list of filters to combine. Must contain at least one filter. + pub filters: Vec, +} + +impl Part for CompositeFilter {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [commit datasets](struct.DatasetCommitCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct CommitRequest { + /// no description provided + #[serde(alias="ignoreReadOnly")] + pub ignore_read_only: Option, + /// The transaction identifier, returned by a call to beginTransaction. Must be set when mode is TRANSACTIONAL. + pub transaction: Option, + /// The type of commit to perform. Either TRANSACTIONAL or NON_TRANSACTIONAL. + pub mode: Option, + /// The mutation to perform. Optional. + pub mutation: Option, +} + +impl RequestValue for CommitRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [run query datasets](struct.DatasetRunQueryCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct RunQueryRequest { + /// The query to run. Either this field or field gql_query must be set, but not both. + pub query: Option, + /// Entities are partitioned into subsets, identified by a dataset (usually implicitly specified by the project) and namespace ID. Queries are scoped to a single partition. This partition ID is normalized with the standard default context partition ID, but all other partition IDs in RunQueryRequest are normalized with this partition ID as the context partition ID. + #[serde(alias="partitionId")] + pub partition_id: Option, + /// The GQL query to run. Either this field or field query must be set, but not both. + #[serde(alias="gqlQuery")] + pub gql_query: Option, + /// The options for this query. + #[serde(alias="readOptions")] + pub read_options: Option, +} + +impl RequestValue for RunQueryRequest {} + + +/// A representation of a kind. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct KindExpression { + /// The name of the kind. + pub name: String, +} + +impl Part for KindExpression {} + + +/// A binding argument for a GQL query. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct GqlQueryArg { + /// no description provided + pub cursor: String, + /// Must match regex "[A-Za-z_$][A-Za-z_$0-9]*". Must not match regex "__.*__". Must not be "". + pub name: String, + /// no description provided + pub value: Value, +} + +impl Part for GqlQueryArg {} + + +/// An entity. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Entity { + /// The entity's properties. + pub properties: HashMap, + /// The entity's key. + /// + /// An entity must have a key, unless otherwise documented (for example, an entity in Value.entityValue may have no key). An entity's kind is its key's path's last element's kind, or null if it has no key. + pub key: Key, +} + +impl Part for Entity {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [rollback datasets](struct.DatasetRollbackCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct RollbackRequest { + /// The transaction identifier, returned by a call to beginTransaction. + pub transaction: Option, +} + +impl RequestValue for RollbackRequest {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [begin transaction datasets](struct.DatasetBeginTransactionCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct BeginTransactionRequest { + /// The transaction isolation level. Either snapshot or serializable. The default isolation level is snapshot isolation, which means that another transaction may not concurrently modify the data that is modified by this transaction. Optionally, a transaction can request to be made serializable which means that another transaction cannot concurrently modify the data that is read or modified by this transaction. + #[serde(alias="isolationLevel")] + pub isolation_level: Option, +} + +impl RequestValue for BeginTransactionRequest {} + + +/// The desired order for a specific property. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct PropertyOrder { + /// The direction to order by. One of ascending or descending. Optional, defaults to ascending. + pub direction: String, + /// The property to order by. + pub property: PropertyReference, +} + +impl Part for PropertyOrder {} + + +/// A query. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct Query { + /// A starting point for the query results. Optional. Query cursors are returned in query result batches. + #[serde(alias="startCursor")] + pub start_cursor: String, + /// The kinds to query (if empty, returns entities from all kinds). + pub kinds: Vec, + /// The projection to return. If not set the entire entity is returned. + pub projection: Vec, + /// The properties to group by (if empty, no grouping is applied to the result set). + #[serde(alias="groupBy")] + pub group_by: Vec, + /// The filter to apply (optional). + pub filter: Filter, + /// The maximum number of results to return. Applies after all other constraints. Optional. + pub limit: i32, + /// The number of results to skip. Applies before limit, but after all other constraints (optional, defaults to 0). + pub offset: i32, + /// An ending point for the query results. Optional. Query cursors are returned in query result batches. + #[serde(alias="endCursor")] + pub end_cursor: String, + /// The order to apply to the query results (if empty, order is unspecified). + pub order: Vec, +} + +impl Part for Query {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *dataset* resources. +/// It is not used directly, but through the `Datastore` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-datastore1_beta2" as datastore1_beta2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use datastore1_beta2::Datastore; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `allocate_ids(...)`, `begin_transaction(...)`, `commit(...)`, `lookup(...)`, `rollback(...)` and `run_query(...)` +/// // to build up your call. +/// let rb = hub.datasets(); +/// # } +/// ``` +pub struct DatasetMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DatasetMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Commit a transaction, optionally creating, deleting or modifying some entities. + pub fn commit(&self, request: &CommitRequest, dataset_id: &str) -> DatasetCommitCall<'a, C, NC, A> { + DatasetCommitCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Allocate IDs for incomplete keys (useful for referencing an entity before it is inserted). + pub fn allocate_ids(&self, request: &AllocateIdsRequest, dataset_id: &str) -> DatasetAllocateIdCall<'a, C, NC, A> { + DatasetAllocateIdCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Roll back a transaction. + pub fn rollback(&self, request: &RollbackRequest, dataset_id: &str) -> DatasetRollbackCall<'a, C, NC, A> { + DatasetRollbackCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Look up some entities by key. + pub fn lookup(&self, request: &LookupRequest, dataset_id: &str) -> DatasetLookupCall<'a, C, NC, A> { + DatasetLookupCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Query for entities. + pub fn run_query(&self, request: &RunQueryRequest, dataset_id: &str) -> DatasetRunQueryCall<'a, C, NC, A> { + DatasetRunQueryCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Begin a new transaction. + pub fn begin_transaction(&self, request: &BeginTransactionRequest, dataset_id: &str) -> DatasetBeginTransactionCall<'a, C, NC, A> { + DatasetBeginTransactionCall { + hub: self.hub, + _request: request.clone(), + _dataset_id: dataset_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Commit a transaction, optionally creating, deleting or modifying some entities. +/// +/// A builder for the *commit* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::CommitRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CommitRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().commit(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetCommitCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: CommitRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetCommitCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetCommitCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommitResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.commit", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/commit".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CommitRequest) -> DatasetCommitCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetCommitCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetCommitCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetCommitCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetCommitCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Allocate IDs for incomplete keys (useful for referencing an entity before it is inserted). +/// +/// A builder for the *allocateIds* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::AllocateIdsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AllocateIdsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().allocate_ids(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetAllocateIdCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: AllocateIdsRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetAllocateIdCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetAllocateIdCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AllocateIdsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.allocateIds", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/allocateIds".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AllocateIdsRequest) -> DatasetAllocateIdCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetAllocateIdCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetAllocateIdCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetAllocateIdCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetAllocateIdCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Roll back a transaction. +/// +/// A builder for the *rollback* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::RollbackRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: RollbackRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().rollback(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetRollbackCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: RollbackRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetRollbackCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetRollbackCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RollbackResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.rollback", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/rollback".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &RollbackRequest) -> DatasetRollbackCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetRollbackCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetRollbackCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetRollbackCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetRollbackCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Look up some entities by key. +/// +/// A builder for the *lookup* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::LookupRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: LookupRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().lookup(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetLookupCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: LookupRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetLookupCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetLookupCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LookupResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.lookup", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/lookup".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &LookupRequest) -> DatasetLookupCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetLookupCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetLookupCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetLookupCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetLookupCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Query for entities. +/// +/// A builder for the *runQuery* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::RunQueryRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: RunQueryRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().run_query(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetRunQueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: RunQueryRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetRunQueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetRunQueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RunQueryResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.runQuery", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/runQuery".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &RunQueryRequest) -> DatasetRunQueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetRunQueryCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetRunQueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetRunQueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetRunQueryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Begin a new transaction. +/// +/// A builder for the *beginTransaction* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-datastore1_beta2" as datastore1_beta2; +/// use datastore1_beta2::BeginTransactionRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use datastore1_beta2::Datastore; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Datastore::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: BeginTransactionRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.datasets().begin_transaction(&req, "datasetId") +/// .doit(); +/// # } +/// ``` +pub struct DatasetBeginTransactionCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Datastore, + _request: BeginTransactionRequest, + _dataset_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DatasetBeginTransactionCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DatasetBeginTransactionCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BeginTransactionResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "datastore.datasets.beginTransaction", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + for &field in ["alt", "datasetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/datastore/v1beta2/datasets/{datasetId}/beginTransaction".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &BeginTransactionRequest) -> DatasetBeginTransactionCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the dataset. + pub fn dataset_id(mut self, new_value: &str) -> DatasetBeginTransactionCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetBeginTransactionCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DatasetBeginTransactionCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetBeginTransactionCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/deploymentmanager2_beta1/Cargo.toml b/gen/deploymentmanager2_beta1/Cargo.toml new file mode 100644 index 0000000000..cf96e40f39 --- /dev/null +++ b/gen/deploymentmanager2_beta1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-deploymentmanager2_beta1" +version = "0.1.0+20141215" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with deploymentmanager (protocol v2beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2_beta1" +homepage = "https://developers.google.com/deployment-manager/" +documentation = "http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1" +license = "MIT" +keywords = ["deploymentmanager", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/deploymentmanager2_beta1/LICENSE.md b/gen/deploymentmanager2_beta1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/deploymentmanager2_beta1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/deploymentmanager2_beta1/README.md b/gen/deploymentmanager2_beta1/README.md new file mode 100644 index 0000000000..88d14e3071 --- /dev/null +++ b/gen/deploymentmanager2_beta1/README.md @@ -0,0 +1,176 @@ + +The `google-deploymentmanager2_beta1` library allows access to all features of the *Google deploymentmanager* service. + +This documentation was generated from *deploymentmanager* crate version *0.1.0+20141215*, where *20141215* is the exact revision of the *deploymentmanager:v2beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *deploymentmanager* *v2_beta1* API can be found at the +[official documentation site](https://developers.google.com/deployment-manager/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Deploymentmanager.html) ... + +* [deployments](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Deployment.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.DeploymentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.DeploymentGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.DeploymentInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.DeploymentListCall.html) +* [manifests](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Manifest.html) + * [*get*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.ManifestGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.ManifestListCall.html) +* [operations](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Operation.html) + * [*get*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.OperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.OperationListCall.html) +* [resources](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.ResourceType.html) + * [*get*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.ResourceGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.ResourceListCall.html) +* [types](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Type.html) + * [*list*](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.TypeListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/struct.Deploymentmanager.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.operations().list(...).doit() +let r = hub.deployments().delete(...).doit() +let r = hub.operations().get(...).doit() +let r = hub.deployments().insert(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-deploymentmanager2_beta1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +use deploymentmanager2_beta1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use deploymentmanager2_beta1::Deploymentmanager; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.operations().list("project") + .page_token("sit") + .max_results(-65) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **deploymentmanager2_beta1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/deploymentmanager2_beta1/src/cmn.rs b/gen/deploymentmanager2_beta1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/deploymentmanager2_beta1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/deploymentmanager2_beta1/src/lib.rs b/gen/deploymentmanager2_beta1/src/lib.rs new file mode 100644 index 0000000000..e4310b498c --- /dev/null +++ b/gen/deploymentmanager2_beta1/src/lib.rs @@ -0,0 +1,3893 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *deploymentmanager* crate version *0.1.0+20141215*, where *20141215* is the exact revision of the *deploymentmanager:v2beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *deploymentmanager* *v2_beta1* API can be found at the +//! [official documentation site](https://developers.google.com/deployment-manager/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2_beta1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Deploymentmanager.html) ... +//! +//! * [deployments](struct.Deployment.html) +//! * [*delete*](struct.DeploymentDeleteCall.html), [*get*](struct.DeploymentGetCall.html), [*insert*](struct.DeploymentInsertCall.html) and [*list*](struct.DeploymentListCall.html) +//! * [manifests](struct.Manifest.html) +//! * [*get*](struct.ManifestGetCall.html) and [*list*](struct.ManifestListCall.html) +//! * [operations](struct.Operation.html) +//! * [*get*](struct.OperationGetCall.html) and [*list*](struct.OperationListCall.html) +//! * [resources](struct.ResourceType.html) +//! * [*get*](struct.ResourceGetCall.html) and [*list*](struct.ResourceListCall.html) +//! * [types](struct.Type.html) +//! * [*list*](struct.TypeListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Deploymentmanager.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.operations().list(...).doit() +//! let r = hub.deployments().delete(...).doit() +//! let r = hub.operations().get(...).doit() +//! let r = hub.deployments().insert(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-deploymentmanager2_beta1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +//! use deploymentmanager2_beta1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use deploymentmanager2_beta1::Deploymentmanager; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.operations().list("project") +//! .page_token("et") +//! .max_results(-18) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your Google Cloud Platform management resources and deployment status information + NdevCloudmanReadonly, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, + + /// View and manage your Google Cloud Platform management resources and deployment status information + NdevCloudman, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::NdevCloudmanReadonly => "https://www.googleapis.com/auth/ndev.cloudman.readonly", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::NdevCloudman => "https://www.googleapis.com/auth/ndev.cloudman", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::NdevCloudmanReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Deploymentmanager related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// use deploymentmanager2_beta1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.operations().list("project") +/// .page_token("accusam") +/// .max_results(-8) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Deploymentmanager { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Deploymentmanager {} + +impl<'a, C, NC, A> Deploymentmanager + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Deploymentmanager { + Deploymentmanager { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn deployments(&'a self) -> DeploymentMethods<'a, C, NC, A> { + DeploymentMethods { hub: &self } + } + pub fn manifests(&'a self) -> ManifestMethods<'a, C, NC, A> { + ManifestMethods { hub: &self } + } + pub fn operations(&'a self) -> OperationMethods<'a, C, NC, A> { + OperationMethods { hub: &self } + } + pub fn resources(&'a self) -> ResourceMethods<'a, C, NC, A> { + ResourceMethods { hub: &self } + } + pub fn types(&'a self) -> TypeMethods<'a, C, NC, A> { + TypeMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get resources](struct.ResourceGetCall.html) (response) +/// * [list resources](struct.ResourceListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResourceType { + /// [Output Only] A list of any errors that occurred during deployment. + pub errors: Vec, + /// [Output Only] The name of the resource as it appears in the YAML config. + pub name: String, + /// [Output Only] The URL of the actual resource. + pub url: String, + /// [Output Only] URL of the manifest representing the current configuration of this resource. + pub manifest: String, + /// [Output Only] The state of the resource. + pub state: String, + /// [Output Only] The intended state of the resource. + pub intent: String, + /// [Output Only] The type of the resource, for example ?compute.v1.instance?, or ?replicaPools.v1beta2.instanceGroupManager? + #[serde(alias="type")] + pub type_: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, +} + +impl Resource for ResourceType {} +impl ResponseResult for ResourceType {} + + +/// Metadata for this warning in 'key: value' format. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarningsData { + /// A key for the warning data. + pub key: String, + /// A warning data value corresponding to the key. + pub value: String, +} + +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// [Output Only] If warning messages generated during processing of this operation, this field will be populated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationWarnings { + /// Optional human-readable details for this warning. + pub message: String, + /// The warning type identifier for this warning. + pub code: String, + /// Metadata for this warning in 'key: value' format. + pub data: Vec, +} + +impl NestedType for OperationWarnings {} +impl Part for OperationWarnings {} + + +/// A response containing a partial list of resources and a page token used to build the next request if the request has been truncated. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list resources](struct.ResourceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResourcesListResponse { + /// A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Resources contained in this list response. + pub resources: Vec, +} + +impl ResponseResult for ResourcesListResponse {} + + +/// The array of errors encountered while processing this operation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationErrorErrors { + /// An optional, human-readable error message. + pub message: String, + /// The error type identifier for this error. + pub code: String, + /// Indicates the field in the request which caused the error. This property is optional. + pub location: String, +} + +impl NestedType for OperationErrorErrors {} +impl Part for OperationErrorErrors {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list manifests](struct.ManifestListCall.html) (none) +/// * [get manifests](struct.ManifestGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Manifest { + /// [Output Only] The fully-expanded configuration file, including any templates and references. + #[serde(alias="evaluatedConfig")] + pub evaluated_config: String, + /// The YAML configuration for this manifest. + pub config: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Self link for the manifest. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] The name of the manifest. + pub name: String, +} + +impl Resource for Manifest {} +impl ResponseResult for Manifest {} + + +/// [Output Only] If errors occurred during processing of this operation, this field will be populated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationError { + /// The array of errors encountered while processing this operation. + pub errors: Vec, +} + +impl NestedType for OperationError {} +impl Part for OperationError {} + + +/// A response that returns all Types supported by Deployment Manager +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list types](struct.TypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TypesListResponse { + /// Types supported by Deployment Manager + pub types: Vec, +} + +impl ResponseResult for TypesListResponse {} + + +/// A response containing a partial list of deployments and a page token used to build the next request if the request has been truncated. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list deployments](struct.DeploymentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DeploymentsListResponse { + /// A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The deployments contained in this response. + pub deployments: Vec, +} + +impl ResponseResult for DeploymentsListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert deployments](struct.DeploymentInsertCall.html) (request) +/// * [get deployments](struct.DeploymentGetCall.html) (response) +/// * [list deployments](struct.DeploymentListCall.html) (none) +/// * [delete deployments](struct.DeploymentDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Deployment { + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// An optional user-provided description of the deployment. + pub description: Option, + /// [Input Only] The YAML configuration to use in processing this deployment. + /// + /// When you create a deployment, the server creates a new manifest with the given YAML configuration and sets the `manifest` property to the URL of the manifest resource. + #[serde(alias="targetConfig")] + pub target_config: Option, + /// The name of the deployment, which must be unique within the project. + pub name: Option, + /// [Output Only] URL of the manifest representing the full configuration of this deployment. + pub manifest: Option, +} + +impl RequestValue for Deployment {} +impl Resource for Deployment {} +impl ResponseResult for Deployment {} + + +/// A response containing a partial list of operations and a page token used to build the next request if the request has been truncated. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operations](struct.OperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperationsListResponse { + /// A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Operations contained in this list response. + pub operations: Vec, +} + +impl ResponseResult for OperationsListResponse {} + + +/// An operation resource, used to manage asynchronous API requests. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operations](struct.OperationListCall.html) (none) +/// * [delete deployments](struct.DeploymentDeleteCall.html) (response) +/// * [get operations](struct.OperationGetCall.html) (response) +/// * [insert deployments](struct.DeploymentInsertCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Operation { + /// [Output Only] Status of the operation. Can be one of the following: "PENDING", "RUNNING", or "DONE". + pub status: String, + /// [Output Only] The time that this operation was requested. This is in RFC 3339 format. + #[serde(alias="insertTime")] + pub insert_time: String, + /// [Output Only] If warning messages generated during processing of this operation, this field will be populated. + pub warnings: Vec, + /// [Output Only] If operation fails, the HTTP error message returned, e.g. NOT FOUND. + #[serde(alias="httpErrorMessage")] + pub http_error_message: String, + /// [Output Only] Unique target id which identifies a particular incarnation of the target. + #[serde(alias="targetId")] + pub target_id: String, + /// [Output Only] URL of the resource the operation is mutating. + #[serde(alias="targetLink")] + pub target_link: String, + /// [Output Only] The time that this operation was started by the server. This is in RFC 3339 format. + #[serde(alias="startTime")] + pub start_time: String, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(alias="creationTimestamp")] + pub creation_timestamp: String, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: String, + /// [Output Only] Name of the operation. + pub name: String, + /// [Output Only] Self link for the manifest. + #[serde(alias="selfLink")] + pub self_link: String, + /// [Output Only] Type of the operation. Examples include "insert", or "delete" + #[serde(alias="operationType")] + pub operation_type: String, + /// [Output Only] If errors occurred during processing of this operation, this field will be populated. + pub error: OperationError, + /// [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of operations. This should not be used to guess at when the operation will be complete. This number should be monotonically increasing as the operation progresses. + pub progress: i32, + /// [Output Only] The time that this operation was completed. This is in RFC3339 format. + #[serde(alias="endTime")] + pub end_time: String, + /// [Output Only] If operation fails, the HTTP error status code returned, e.g. 404. + #[serde(alias="httpErrorStatusCode")] + pub http_error_status_code: i32, + /// [Output Only] An optional textual description of the current status of the operation. + #[serde(alias="statusMessage")] + pub status_message: String, + /// [Output Only] User who requested the operation, for example "user@example.com" + pub user: String, +} + +impl Resource for Operation {} +impl ResponseResult for Operation {} + + +/// A type supported by Deployment Manager. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list types](struct.TypeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Type { + /// Name of the type. + pub name: Option, +} + +impl Resource for Type {} + + +/// A response containing a partial list of manifests and a page token used to build the next request if the request has been truncated. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list manifests](struct.ManifestListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ManifestsListResponse { + /// A token used to continue a truncated list request. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Manifests contained in this list response. + pub manifests: Vec, +} + +impl ResponseResult for ManifestsListResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *operation* resources. +/// It is not used directly, but through the `Deploymentmanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.operations(); +/// # } +/// ``` +pub struct OperationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for OperationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a specific Operation. + pub fn get(&self, project: &str, operation: &str) -> OperationGetCall<'a, C, NC, A> { + OperationGetCall { + hub: self.hub, + _project: project.to_string(), + _operation: operation.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all Operations for a project. + pub fn list(&self, project: &str) -> OperationListCall<'a, C, NC, A> { + OperationListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *deployment* resources. +/// It is not used directly, but through the `Deploymentmanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.deployments(); +/// # } +/// ``` +pub struct DeploymentMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DeploymentMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeploymentMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates a deployment and all of the resources described by the deployment manifest. + pub fn insert(&self, request: &Deployment, project: &str) -> DeploymentInsertCall<'a, C, NC, A> { + DeploymentInsertCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a specific deployment. + pub fn get(&self, project: &str, deployment: &str) -> DeploymentGetCall<'a, C, NC, A> { + DeploymentGetCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all deployments for a given project. + pub fn list(&self, project: &str) -> DeploymentListCall<'a, C, NC, A> { + DeploymentListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a deployment and all of the resources in the deployment. + pub fn delete(&self, project: &str, deployment: &str) -> DeploymentDeleteCall<'a, C, NC, A> { + DeploymentDeleteCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *type* resources. +/// It is not used directly, but through the `Deploymentmanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.types(); +/// # } +/// ``` +pub struct TypeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for TypeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> TypeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all Types for Deployment Manager. + pub fn list(&self, project: &str) -> TypeListCall<'a, C, NC, A> { + TypeListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *resource* resources. +/// It is not used directly, but through the `Deploymentmanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.resources(); +/// # } +/// ``` +pub struct ResourceMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ResourceMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ResourceMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a single resource. + pub fn get(&self, project: &str, deployment: &str, resource: &str) -> ResourceGetCall<'a, C, NC, A> { + ResourceGetCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all resources in a given deployment. + pub fn list(&self, project: &str, deployment: &str) -> ResourceListCall<'a, C, NC, A> { + ResourceListCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *manifest* resources. +/// It is not used directly, but through the `Deploymentmanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2_beta1::Deploymentmanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.manifests(); +/// # } +/// ``` +pub struct ManifestMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ManifestMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManifestMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all manifests for a given deployment. + pub fn list(&self, project: &str, deployment: &str) -> ManifestListCall<'a, C, NC, A> { + ManifestListCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a specific manifest. + pub fn get(&self, project: &str, deployment: &str, manifest: &str) -> ManifestGetCall<'a, C, NC, A> { + ManifestGetCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.to_string(), + _manifest: manifest.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Gets information about a specific Operation. +/// +/// A builder for the *get* method supported by a *operation* resource. +/// It is not used directly, but through a `OperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.operations().get("project", "operation") +/// .doit(); +/// # } +/// ``` +pub struct OperationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OperationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.operations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("operation", self._operation.to_string())); + for &field in ["alt", "project", "operation"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{operation}", "operation")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "operation"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> OperationGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *operation* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the operation for this request. + pub fn operation(mut self, new_value: &str) -> OperationGetCall<'a, C, NC, A> { + self._operation = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all Operations for a project. +/// +/// A builder for the *list* method supported by a *operation* resource. +/// It is not used directly, but through a `OperationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.operations().list("project") +/// .page_token("labore") +/// .max_results(-9) +/// .doit(); +/// # } +/// ``` +pub struct OperationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OperationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperationsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.operations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> OperationListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. + pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum count of results to be returned. Acceptable values are 0 to 100, inclusive. (Default: 50) + pub fn max_results(mut self, new_value: i32) -> OperationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a deployment and all of the resources described by the deployment manifest. +/// +/// A builder for the *insert* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// use deploymentmanager2_beta1::Deployment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Deployment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.deployments().insert(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _request: Deployment, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeploymentInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeploymentInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.deployments.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Deployment) -> DeploymentInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> DeploymentInsertCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets information about a specific deployment. +/// +/// A builder for the *get* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.deployments().get("project", "deployment") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeploymentGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeploymentGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Deployment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.deployments.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + for &field in ["alt", "project", "deployment"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "deployment"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> DeploymentGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> DeploymentGetCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all deployments for a given project. +/// +/// A builder for the *list* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.deployments().list("project") +/// .page_token("aliquyam") +/// .max_results(-66) +/// .doit(); +/// # } +/// ``` +pub struct DeploymentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeploymentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeploymentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeploymentsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.deployments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> DeploymentListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. + pub fn page_token(mut self, new_value: &str) -> DeploymentListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum count of results to be returned. Acceptable values are 0 to 100, inclusive. (Default: 50) + pub fn max_results(mut self, new_value: i32) -> DeploymentListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a deployment and all of the resources in the deployment. +/// +/// A builder for the *delete* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.deployments().delete("project", "deployment") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DeploymentDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DeploymentDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.deployments.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + for &field in ["alt", "project", "deployment"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "deployment"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> DeploymentDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> DeploymentDeleteCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all Types for Deployment Manager. +/// +/// A builder for the *list* method supported by a *type* resource. +/// It is not used directly, but through a `TypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.types().list("project") +/// .page_token("et") +/// .max_results(-17) +/// .doit(); +/// # } +/// ``` +pub struct TypeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for TypeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> TypeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TypesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.types.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/types".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> TypeListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. + pub fn page_token(mut self, new_value: &str) -> TypeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum count of results to be returned. Acceptable values are 0 to 100, inclusive. (Default: 50) + pub fn max_results(mut self, new_value: i32) -> TypeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TypeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TypeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TypeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets information about a single resource. +/// +/// A builder for the *get* method supported by a *resource* resource. +/// It is not used directly, but through a `ResourceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.resources().get("project", "deployment", "resource") +/// .doit(); +/// # } +/// ``` +pub struct ResourceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ResourceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ResourceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ResourceType)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.resources.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "project", "deployment", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}/resources/{resource}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment"), ("{resource}", "resource")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "deployment", "resource"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> ResourceGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> ResourceGetCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *resource* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the resource for this request. + pub fn resource(mut self, new_value: &str) -> ResourceGetCall<'a, C, NC, A> { + self._resource = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ResourceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ResourceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ResourceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all resources in a given deployment. +/// +/// A builder for the *list* method supported by a *resource* resource. +/// It is not used directly, but through a `ResourceMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.resources().list("project", "deployment") +/// .page_token("aliquyam") +/// .max_results(-9) +/// .doit(); +/// # } +/// ``` +pub struct ResourceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ResourceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ResourceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ResourcesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.resources.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "deployment", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}/resources".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "deployment"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> ResourceListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> ResourceListCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. + pub fn page_token(mut self, new_value: &str) -> ResourceListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum count of results to be returned. Acceptable values are 0 to 100, inclusive. (Default: 50) + pub fn max_results(mut self, new_value: i32) -> ResourceListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ResourceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ResourceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ResourceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all manifests for a given deployment. +/// +/// A builder for the *list* method supported by a *manifest* resource. +/// It is not used directly, but through a `ManifestMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.manifests().list("project", "deployment") +/// .page_token("erat") +/// .max_results(-95) +/// .doit(); +/// # } +/// ``` +pub struct ManifestListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManifestListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManifestListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ManifestsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.manifests.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "deployment", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}/manifests".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "deployment"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> ManifestListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> ManifestListCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Specifies a nextPageToken returned by a previous list request. This token can be used to request the next page of results from a previous list request. + pub fn page_token(mut self, new_value: &str) -> ManifestListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum count of results to be returned. Acceptable values are 0 to 100, inclusive. (Default: 50) + pub fn max_results(mut self, new_value: i32) -> ManifestListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManifestListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManifestListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManifestListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets information about a specific manifest. +/// +/// A builder for the *get* method supported by a *manifest* resource. +/// It is not used directly, but through a `ManifestMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-deploymentmanager2_beta1" as deploymentmanager2_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2_beta1::Deploymentmanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Deploymentmanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.manifests().get("project", "deployment", "manifest") +/// .doit(); +/// # } +/// ``` +pub struct ManifestGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Deploymentmanager, + _project: String, + _deployment: String, + _manifest: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManifestGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManifestGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Manifest)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "deploymentmanager.manifests.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + params.push(("manifest", self._manifest.to_string())); + for &field in ["alt", "project", "deployment", "manifest"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/deploymentmanager/v2beta1/projects/{project}/global/deployments/{deployment}/manifests/{manifest}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{deployment}", "deployment"), ("{manifest}", "manifest")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "deployment", "manifest"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The project ID for this request. + pub fn project(mut self, new_value: &str) -> ManifestGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *deployment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the deployment for this request. + pub fn deployment(mut self, new_value: &str) -> ManifestGetCall<'a, C, NC, A> { + self._deployment = new_value.to_string(); + self + } + /// Sets the *manifest* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The name of the manifest for this request. + pub fn manifest(mut self, new_value: &str) -> ManifestGetCall<'a, C, NC, A> { + self._manifest = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManifestGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManifestGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManifestGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/dfareporting2/Cargo.toml b/gen/dfareporting2/Cargo.toml new file mode 100644 index 0000000000..c79983e82a --- /dev/null +++ b/gen/dfareporting2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-dfareporting2" +version = "0.1.0+20150223" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with dfareporting (protocol v2.0)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2" +homepage = "https://developers.google.com/doubleclick-advertisers/reporting/" +documentation = "http://byron.github.io/google-apis-rs/google-dfareporting2" +license = "MIT" +keywords = ["dfareporting", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/dfareporting2/LICENSE.md b/gen/dfareporting2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/dfareporting2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/dfareporting2/README.md b/gen/dfareporting2/README.md new file mode 100644 index 0000000000..9cea062978 --- /dev/null +++ b/gen/dfareporting2/README.md @@ -0,0 +1,280 @@ + +The `google-dfareporting2` library allows access to all features of the *Google dfareporting* service. + +This documentation was generated from *dfareporting* crate version *0.1.0+20150223*, where *20150223* is the exact revision of the *dfareporting:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *dfareporting* *v2* API can be found at the +[official documentation site](https://developers.google.com/doubleclick-advertisers/reporting/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Dfareporting.html) ... + +* [account active ad summaries](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountActiveAdSummary.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountActiveAdSummaryGetCall.html) +* [account permission groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermissionGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermissionGroupGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermissionGroupListCall.html) +* [account permissions](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermission.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermissionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPermissionListCall.html) +* [account user profiles](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUserProfile.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUserProfileGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUserProfileListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUserProfilePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUserProfileUpdateCall.html) +* [accounts](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Account.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AccountUpdateCall.html) +* [ads](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Ad.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdUpdateCall.html) +* [advertiser groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroup.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGroupUpdateCall.html) +* [advertisers](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Advertiser.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.AdvertiserUpdateCall.html) +* [browsers](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Browser.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.BrowserListCall.html) +* [campaign creative associations](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignCreativeAssociation.html) + * [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignCreativeAssociationInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignCreativeAssociationListCall.html) +* [campaigns](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Campaign.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CampaignUpdateCall.html) +* [change logs](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ChangeLog.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ChangeLogGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ChangeLogListCall.html) +* [cities](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.City.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CityListCall.html) +* [connection types](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ConnectionType.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ConnectionTypeListCall.html) +* [content categories](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategory.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ContentCategoryUpdateCall.html) +* [countries](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Country.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CountryGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CountryListCall.html) +* [creative assets](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeAsset.html) + * [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeAssetInsertCall.html) +* [creative field values](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValue.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValueDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValueGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValueInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValueListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValuePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldValueUpdateCall.html) +* [creative fields](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeField.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeFieldUpdateCall.html) +* [creative groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGroupUpdateCall.html) +* [creatives](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Creative.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeUpdateCall.html) +* [dimension values](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DimensionValue.html) + * [*query*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DimensionValueQueryCall.html) +* [directory site contacts](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySiteContact.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySiteContactGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySiteContactListCall.html) +* [directory sites](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySite.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySiteGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.DirectorySiteListCall.html) +* [event tags](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTag.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.EventTagUpdateCall.html) +* [files](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.File.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FileGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FileListCall.html) +* [floodlight activities](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivity.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityDeleteCall.html), [*generatetag*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGeneratetagCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityUpdateCall.html) +* [floodlight activity groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroup.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightActivityGroupUpdateCall.html) +* [floodlight configurations](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightConfiguration.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightConfigurationGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightConfigurationListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightConfigurationPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FloodlightConfigurationUpdateCall.html) +* [landing pages](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPage.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPageDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPageGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPageInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPageListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPagePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.LandingPageUpdateCall.html) +* [metros](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Metro.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.MetroListCall.html) +* [mobile carriers](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.MobileCarrier.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.MobileCarrierListCall.html) +* [operating system versions](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.OperatingSystemVersion.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.OperatingSystemVersionListCall.html) +* [operating systems](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.OperatingSystem.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.OperatingSystemListCall.html) +* [placement groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGroupUpdateCall.html) +* [placement strategies](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategy.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementStrategyUpdateCall.html) +* [placements](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Placement.html) + * [*generatetags*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGeneratetagCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlacementUpdateCall.html) +* [platform types](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlatformType.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PlatformTypeListCall.html) +* [postal codes](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PostalCode.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.PostalCodeListCall.html) +* [regions](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Region.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.RegionListCall.html) +* [reports](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Report.html) + * [*compatible fields query*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportCompatibleFieldQueryCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportDeleteCall.html), [*files get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportFileGetCall.html), [*files list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportFileListCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportPatchCall.html), [*run*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportRunCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportUpdateCall.html) +* [sites](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Site.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SiteGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SiteInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SiteListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SitePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SiteUpdateCall.html) +* [sizes](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Size.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SizeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SizeInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SizeListCall.html) +* [subaccounts](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Subaccount.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SubaccountGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SubaccountInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SubaccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SubaccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.SubaccountUpdateCall.html) +* [user profiles](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserProfile.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserProfileGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserProfileListCall.html) +* [user role permission groups](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermissionGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermissionGroupGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermissionGroupListCall.html) +* [user role permissions](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermission.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermissionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePermissionListCall.html) +* [user roles](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRole.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRoleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRoleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRoleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRoleListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRolePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.UserRoleUpdateCall.html) + + +Upload supported by ... + +* [*insert creative assets*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.CreativeAssetInsertCall.html) + +Download supported by ... + +* [*get files*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.FileGetCall.html) +* [*files get reports*](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.ReportFileGetCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-dfareporting2/struct.Dfareporting.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.reports().run(...).doit() +let r = hub.reports().get(...).doit() +let r = hub.reports().list(...).doit() +let r = hub.reports().delete(...).doit() +let r = hub.reports().files_list(...).doit() +let r = hub.reports().insert(...).doit() +let r = hub.reports().patch(...).doit() +let r = hub.reports().compatible_fields_query(...).doit() +let r = hub.reports().update(...).doit() +let r = hub.reports().files_get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-dfareporting2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-dfareporting2" as dfareporting2; +use dfareporting2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use dfareporting2::Dfareporting; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Dfareporting::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.reports().list("profileId") + .sort_order("sit") + .sort_field("Stet") + .scope("sed") + .page_token("et") + .max_results(-18) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-dfareporting2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-dfareporting2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-dfareporting2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-dfareporting2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **dfareporting2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/dfareporting2/src/cmn.rs b/gen/dfareporting2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/dfareporting2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/dfareporting2/src/lib.rs b/gen/dfareporting2/src/lib.rs new file mode 100644 index 0000000000..457553a397 --- /dev/null +++ b/gen/dfareporting2/src/lib.rs @@ -0,0 +1,56192 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *dfareporting* crate version *0.1.0+20150223*, where *20150223* is the exact revision of the *dfareporting:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *dfareporting* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/doubleclick-advertisers/reporting/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Dfareporting.html) ... +//! +//! * [account active ad summaries](struct.AccountActiveAdSummary.html) +//! * [*get*](struct.AccountActiveAdSummaryGetCall.html) +//! * [account permission groups](struct.AccountPermissionGroup.html) +//! * [*get*](struct.AccountPermissionGroupGetCall.html) and [*list*](struct.AccountPermissionGroupListCall.html) +//! * [account permissions](struct.AccountPermission.html) +//! * [*get*](struct.AccountPermissionGetCall.html) and [*list*](struct.AccountPermissionListCall.html) +//! * [account user profiles](struct.AccountUserProfile.html) +//! * [*get*](struct.AccountUserProfileGetCall.html), [*list*](struct.AccountUserProfileListCall.html), [*patch*](struct.AccountUserProfilePatchCall.html) and [*update*](struct.AccountUserProfileUpdateCall.html) +//! * [accounts](struct.Account.html) +//! * [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*patch*](struct.AccountPatchCall.html) and [*update*](struct.AccountUpdateCall.html) +//! * [ads](struct.Ad.html) +//! * [*get*](struct.AdGetCall.html), [*insert*](struct.AdInsertCall.html), [*list*](struct.AdListCall.html), [*patch*](struct.AdPatchCall.html) and [*update*](struct.AdUpdateCall.html) +//! * [advertiser groups](struct.AdvertiserGroup.html) +//! * [*delete*](struct.AdvertiserGroupDeleteCall.html), [*get*](struct.AdvertiserGroupGetCall.html), [*insert*](struct.AdvertiserGroupInsertCall.html), [*list*](struct.AdvertiserGroupListCall.html), [*patch*](struct.AdvertiserGroupPatchCall.html) and [*update*](struct.AdvertiserGroupUpdateCall.html) +//! * [advertisers](struct.Advertiser.html) +//! * [*get*](struct.AdvertiserGetCall.html), [*insert*](struct.AdvertiserInsertCall.html), [*list*](struct.AdvertiserListCall.html), [*patch*](struct.AdvertiserPatchCall.html) and [*update*](struct.AdvertiserUpdateCall.html) +//! * [browsers](struct.Browser.html) +//! * [*list*](struct.BrowserListCall.html) +//! * [campaign creative associations](struct.CampaignCreativeAssociation.html) +//! * [*insert*](struct.CampaignCreativeAssociationInsertCall.html) and [*list*](struct.CampaignCreativeAssociationListCall.html) +//! * [campaigns](struct.Campaign.html) +//! * [*get*](struct.CampaignGetCall.html), [*insert*](struct.CampaignInsertCall.html), [*list*](struct.CampaignListCall.html), [*patch*](struct.CampaignPatchCall.html) and [*update*](struct.CampaignUpdateCall.html) +//! * [change logs](struct.ChangeLog.html) +//! * [*get*](struct.ChangeLogGetCall.html) and [*list*](struct.ChangeLogListCall.html) +//! * [cities](struct.City.html) +//! * [*list*](struct.CityListCall.html) +//! * [connection types](struct.ConnectionType.html) +//! * [*list*](struct.ConnectionTypeListCall.html) +//! * [content categories](struct.ContentCategory.html) +//! * [*delete*](struct.ContentCategoryDeleteCall.html), [*get*](struct.ContentCategoryGetCall.html), [*insert*](struct.ContentCategoryInsertCall.html), [*list*](struct.ContentCategoryListCall.html), [*patch*](struct.ContentCategoryPatchCall.html) and [*update*](struct.ContentCategoryUpdateCall.html) +//! * [countries](struct.Country.html) +//! * [*get*](struct.CountryGetCall.html) and [*list*](struct.CountryListCall.html) +//! * [creative assets](struct.CreativeAsset.html) +//! * [*insert*](struct.CreativeAssetInsertCall.html) +//! * [creative field values](struct.CreativeFieldValue.html) +//! * [*delete*](struct.CreativeFieldValueDeleteCall.html), [*get*](struct.CreativeFieldValueGetCall.html), [*insert*](struct.CreativeFieldValueInsertCall.html), [*list*](struct.CreativeFieldValueListCall.html), [*patch*](struct.CreativeFieldValuePatchCall.html) and [*update*](struct.CreativeFieldValueUpdateCall.html) +//! * [creative fields](struct.CreativeField.html) +//! * [*delete*](struct.CreativeFieldDeleteCall.html), [*get*](struct.CreativeFieldGetCall.html), [*insert*](struct.CreativeFieldInsertCall.html), [*list*](struct.CreativeFieldListCall.html), [*patch*](struct.CreativeFieldPatchCall.html) and [*update*](struct.CreativeFieldUpdateCall.html) +//! * [creative groups](struct.CreativeGroup.html) +//! * [*get*](struct.CreativeGroupGetCall.html), [*insert*](struct.CreativeGroupInsertCall.html), [*list*](struct.CreativeGroupListCall.html), [*patch*](struct.CreativeGroupPatchCall.html) and [*update*](struct.CreativeGroupUpdateCall.html) +//! * [creatives](struct.Creative.html) +//! * [*get*](struct.CreativeGetCall.html), [*insert*](struct.CreativeInsertCall.html), [*list*](struct.CreativeListCall.html), [*patch*](struct.CreativePatchCall.html) and [*update*](struct.CreativeUpdateCall.html) +//! * [dimension values](struct.DimensionValue.html) +//! * [*query*](struct.DimensionValueQueryCall.html) +//! * [directory site contacts](struct.DirectorySiteContact.html) +//! * [*get*](struct.DirectorySiteContactGetCall.html) and [*list*](struct.DirectorySiteContactListCall.html) +//! * [directory sites](struct.DirectorySite.html) +//! * [*get*](struct.DirectorySiteGetCall.html) and [*list*](struct.DirectorySiteListCall.html) +//! * [event tags](struct.EventTag.html) +//! * [*delete*](struct.EventTagDeleteCall.html), [*get*](struct.EventTagGetCall.html), [*insert*](struct.EventTagInsertCall.html), [*list*](struct.EventTagListCall.html), [*patch*](struct.EventTagPatchCall.html) and [*update*](struct.EventTagUpdateCall.html) +//! * [files](struct.File.html) +//! * [*get*](struct.FileGetCall.html) and [*list*](struct.FileListCall.html) +//! * [floodlight activities](struct.FloodlightActivity.html) +//! * [*delete*](struct.FloodlightActivityDeleteCall.html), [*generatetag*](struct.FloodlightActivityGeneratetagCall.html), [*get*](struct.FloodlightActivityGetCall.html), [*insert*](struct.FloodlightActivityInsertCall.html), [*list*](struct.FloodlightActivityListCall.html), [*patch*](struct.FloodlightActivityPatchCall.html) and [*update*](struct.FloodlightActivityUpdateCall.html) +//! * [floodlight activity groups](struct.FloodlightActivityGroup.html) +//! * [*delete*](struct.FloodlightActivityGroupDeleteCall.html), [*get*](struct.FloodlightActivityGroupGetCall.html), [*insert*](struct.FloodlightActivityGroupInsertCall.html), [*list*](struct.FloodlightActivityGroupListCall.html), [*patch*](struct.FloodlightActivityGroupPatchCall.html) and [*update*](struct.FloodlightActivityGroupUpdateCall.html) +//! * [floodlight configurations](struct.FloodlightConfiguration.html) +//! * [*get*](struct.FloodlightConfigurationGetCall.html), [*list*](struct.FloodlightConfigurationListCall.html), [*patch*](struct.FloodlightConfigurationPatchCall.html) and [*update*](struct.FloodlightConfigurationUpdateCall.html) +//! * [landing pages](struct.LandingPage.html) +//! * [*delete*](struct.LandingPageDeleteCall.html), [*get*](struct.LandingPageGetCall.html), [*insert*](struct.LandingPageInsertCall.html), [*list*](struct.LandingPageListCall.html), [*patch*](struct.LandingPagePatchCall.html) and [*update*](struct.LandingPageUpdateCall.html) +//! * [metros](struct.Metro.html) +//! * [*list*](struct.MetroListCall.html) +//! * [mobile carriers](struct.MobileCarrier.html) +//! * [*list*](struct.MobileCarrierListCall.html) +//! * [operating system versions](struct.OperatingSystemVersion.html) +//! * [*list*](struct.OperatingSystemVersionListCall.html) +//! * [operating systems](struct.OperatingSystem.html) +//! * [*list*](struct.OperatingSystemListCall.html) +//! * [placement groups](struct.PlacementGroup.html) +//! * [*get*](struct.PlacementGroupGetCall.html), [*insert*](struct.PlacementGroupInsertCall.html), [*list*](struct.PlacementGroupListCall.html), [*patch*](struct.PlacementGroupPatchCall.html) and [*update*](struct.PlacementGroupUpdateCall.html) +//! * [placement strategies](struct.PlacementStrategy.html) +//! * [*delete*](struct.PlacementStrategyDeleteCall.html), [*get*](struct.PlacementStrategyGetCall.html), [*insert*](struct.PlacementStrategyInsertCall.html), [*list*](struct.PlacementStrategyListCall.html), [*patch*](struct.PlacementStrategyPatchCall.html) and [*update*](struct.PlacementStrategyUpdateCall.html) +//! * [placements](struct.Placement.html) +//! * [*generatetags*](struct.PlacementGeneratetagCall.html), [*get*](struct.PlacementGetCall.html), [*insert*](struct.PlacementInsertCall.html), [*list*](struct.PlacementListCall.html), [*patch*](struct.PlacementPatchCall.html) and [*update*](struct.PlacementUpdateCall.html) +//! * [platform types](struct.PlatformType.html) +//! * [*list*](struct.PlatformTypeListCall.html) +//! * [postal codes](struct.PostalCode.html) +//! * [*list*](struct.PostalCodeListCall.html) +//! * [regions](struct.Region.html) +//! * [*list*](struct.RegionListCall.html) +//! * [reports](struct.Report.html) +//! * [*compatible fields query*](struct.ReportCompatibleFieldQueryCall.html), [*delete*](struct.ReportDeleteCall.html), [*files get*](struct.ReportFileGetCall.html), [*files list*](struct.ReportFileListCall.html), [*get*](struct.ReportGetCall.html), [*insert*](struct.ReportInsertCall.html), [*list*](struct.ReportListCall.html), [*patch*](struct.ReportPatchCall.html), [*run*](struct.ReportRunCall.html) and [*update*](struct.ReportUpdateCall.html) +//! * [sites](struct.Site.html) +//! * [*get*](struct.SiteGetCall.html), [*insert*](struct.SiteInsertCall.html), [*list*](struct.SiteListCall.html), [*patch*](struct.SitePatchCall.html) and [*update*](struct.SiteUpdateCall.html) +//! * [sizes](struct.Size.html) +//! * [*get*](struct.SizeGetCall.html), [*insert*](struct.SizeInsertCall.html) and [*list*](struct.SizeListCall.html) +//! * [subaccounts](struct.Subaccount.html) +//! * [*get*](struct.SubaccountGetCall.html), [*insert*](struct.SubaccountInsertCall.html), [*list*](struct.SubaccountListCall.html), [*patch*](struct.SubaccountPatchCall.html) and [*update*](struct.SubaccountUpdateCall.html) +//! * [user profiles](struct.UserProfile.html) +//! * [*get*](struct.UserProfileGetCall.html) and [*list*](struct.UserProfileListCall.html) +//! * [user role permission groups](struct.UserRolePermissionGroup.html) +//! * [*get*](struct.UserRolePermissionGroupGetCall.html) and [*list*](struct.UserRolePermissionGroupListCall.html) +//! * [user role permissions](struct.UserRolePermission.html) +//! * [*get*](struct.UserRolePermissionGetCall.html) and [*list*](struct.UserRolePermissionListCall.html) +//! * [user roles](struct.UserRole.html) +//! * [*delete*](struct.UserRoleDeleteCall.html), [*get*](struct.UserRoleGetCall.html), [*insert*](struct.UserRoleInsertCall.html), [*list*](struct.UserRoleListCall.html), [*patch*](struct.UserRolePatchCall.html) and [*update*](struct.UserRoleUpdateCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*insert creative assets*](struct.CreativeAssetInsertCall.html) +//! +//! Download supported by ... +//! +//! * [*get files*](struct.FileGetCall.html) +//! * [*files get reports*](struct.ReportFileGetCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Dfareporting.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.reports().run(...).doit() +//! let r = hub.reports().get(...).doit() +//! let r = hub.reports().list(...).doit() +//! let r = hub.reports().delete(...).doit() +//! let r = hub.reports().files_list(...).doit() +//! let r = hub.reports().insert(...).doit() +//! let r = hub.reports().patch(...).doit() +//! let r = hub.reports().compatible_fields_query(...).doit() +//! let r = hub.reports().update(...).doit() +//! let r = hub.reports().files_get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-dfareporting2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-dfareporting2" as dfareporting2; +//! use dfareporting2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use dfareporting2::Dfareporting; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Dfareporting::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.reports().list("profileId") +//! .sort_order("accusam") +//! .sort_field("takimata") +//! .scope("justo") +//! .page_token("amet.") +//! .max_results(-81) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your DoubleClick Campaign Manager's (DCM) display ad campaigns + Dfatrafficking, + + /// View and manage DoubleClick for Advertisers reports + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Dfatrafficking => "https://www.googleapis.com/auth/dfatrafficking", + Scope::Full => "https://www.googleapis.com/auth/dfareporting", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Dfareporting related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().list("profileId") +/// .sort_order("sea") +/// .sort_field("nonumy") +/// .scope("dolores") +/// .page_token("gubergren") +/// .max_results(-95) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Dfareporting { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Dfareporting {} + +impl<'a, C, NC, A> Dfareporting + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Dfareporting { + Dfareporting { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn account_active_ad_summaries(&'a self) -> AccountActiveAdSummaryMethods<'a, C, NC, A> { + AccountActiveAdSummaryMethods { hub: &self } + } + pub fn account_permission_groups(&'a self) -> AccountPermissionGroupMethods<'a, C, NC, A> { + AccountPermissionGroupMethods { hub: &self } + } + pub fn account_permissions(&'a self) -> AccountPermissionMethods<'a, C, NC, A> { + AccountPermissionMethods { hub: &self } + } + pub fn account_user_profiles(&'a self) -> AccountUserProfileMethods<'a, C, NC, A> { + AccountUserProfileMethods { hub: &self } + } + pub fn accounts(&'a self) -> AccountMethods<'a, C, NC, A> { + AccountMethods { hub: &self } + } + pub fn ads(&'a self) -> AdMethods<'a, C, NC, A> { + AdMethods { hub: &self } + } + pub fn advertiser_groups(&'a self) -> AdvertiserGroupMethods<'a, C, NC, A> { + AdvertiserGroupMethods { hub: &self } + } + pub fn advertisers(&'a self) -> AdvertiserMethods<'a, C, NC, A> { + AdvertiserMethods { hub: &self } + } + pub fn browsers(&'a self) -> BrowserMethods<'a, C, NC, A> { + BrowserMethods { hub: &self } + } + pub fn campaign_creative_associations(&'a self) -> CampaignCreativeAssociationMethods<'a, C, NC, A> { + CampaignCreativeAssociationMethods { hub: &self } + } + pub fn campaigns(&'a self) -> CampaignMethods<'a, C, NC, A> { + CampaignMethods { hub: &self } + } + pub fn change_logs(&'a self) -> ChangeLogMethods<'a, C, NC, A> { + ChangeLogMethods { hub: &self } + } + pub fn cities(&'a self) -> CityMethods<'a, C, NC, A> { + CityMethods { hub: &self } + } + pub fn connection_types(&'a self) -> ConnectionTypeMethods<'a, C, NC, A> { + ConnectionTypeMethods { hub: &self } + } + pub fn content_categories(&'a self) -> ContentCategoryMethods<'a, C, NC, A> { + ContentCategoryMethods { hub: &self } + } + pub fn countries(&'a self) -> CountryMethods<'a, C, NC, A> { + CountryMethods { hub: &self } + } + pub fn creative_assets(&'a self) -> CreativeAssetMethods<'a, C, NC, A> { + CreativeAssetMethods { hub: &self } + } + pub fn creative_field_values(&'a self) -> CreativeFieldValueMethods<'a, C, NC, A> { + CreativeFieldValueMethods { hub: &self } + } + pub fn creative_fields(&'a self) -> CreativeFieldMethods<'a, C, NC, A> { + CreativeFieldMethods { hub: &self } + } + pub fn creative_groups(&'a self) -> CreativeGroupMethods<'a, C, NC, A> { + CreativeGroupMethods { hub: &self } + } + pub fn creatives(&'a self) -> CreativeMethods<'a, C, NC, A> { + CreativeMethods { hub: &self } + } + pub fn dimension_values(&'a self) -> DimensionValueMethods<'a, C, NC, A> { + DimensionValueMethods { hub: &self } + } + pub fn directory_site_contacts(&'a self) -> DirectorySiteContactMethods<'a, C, NC, A> { + DirectorySiteContactMethods { hub: &self } + } + pub fn directory_sites(&'a self) -> DirectorySiteMethods<'a, C, NC, A> { + DirectorySiteMethods { hub: &self } + } + pub fn event_tags(&'a self) -> EventTagMethods<'a, C, NC, A> { + EventTagMethods { hub: &self } + } + pub fn files(&'a self) -> FileMethods<'a, C, NC, A> { + FileMethods { hub: &self } + } + pub fn floodlight_activities(&'a self) -> FloodlightActivityMethods<'a, C, NC, A> { + FloodlightActivityMethods { hub: &self } + } + pub fn floodlight_activity_groups(&'a self) -> FloodlightActivityGroupMethods<'a, C, NC, A> { + FloodlightActivityGroupMethods { hub: &self } + } + pub fn floodlight_configurations(&'a self) -> FloodlightConfigurationMethods<'a, C, NC, A> { + FloodlightConfigurationMethods { hub: &self } + } + pub fn landing_pages(&'a self) -> LandingPageMethods<'a, C, NC, A> { + LandingPageMethods { hub: &self } + } + pub fn metros(&'a self) -> MetroMethods<'a, C, NC, A> { + MetroMethods { hub: &self } + } + pub fn mobile_carriers(&'a self) -> MobileCarrierMethods<'a, C, NC, A> { + MobileCarrierMethods { hub: &self } + } + pub fn operating_system_versions(&'a self) -> OperatingSystemVersionMethods<'a, C, NC, A> { + OperatingSystemVersionMethods { hub: &self } + } + pub fn operating_systems(&'a self) -> OperatingSystemMethods<'a, C, NC, A> { + OperatingSystemMethods { hub: &self } + } + pub fn placement_groups(&'a self) -> PlacementGroupMethods<'a, C, NC, A> { + PlacementGroupMethods { hub: &self } + } + pub fn placement_strategies(&'a self) -> PlacementStrategyMethods<'a, C, NC, A> { + PlacementStrategyMethods { hub: &self } + } + pub fn placements(&'a self) -> PlacementMethods<'a, C, NC, A> { + PlacementMethods { hub: &self } + } + pub fn platform_types(&'a self) -> PlatformTypeMethods<'a, C, NC, A> { + PlatformTypeMethods { hub: &self } + } + pub fn postal_codes(&'a self) -> PostalCodeMethods<'a, C, NC, A> { + PostalCodeMethods { hub: &self } + } + pub fn regions(&'a self) -> RegionMethods<'a, C, NC, A> { + RegionMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, NC, A> { + ReportMethods { hub: &self } + } + pub fn sites(&'a self) -> SiteMethods<'a, C, NC, A> { + SiteMethods { hub: &self } + } + pub fn sizes(&'a self) -> SizeMethods<'a, C, NC, A> { + SizeMethods { hub: &self } + } + pub fn subaccounts(&'a self) -> SubaccountMethods<'a, C, NC, A> { + SubaccountMethods { hub: &self } + } + pub fn user_profiles(&'a self) -> UserProfileMethods<'a, C, NC, A> { + UserProfileMethods { hub: &self } + } + pub fn user_role_permission_groups(&'a self) -> UserRolePermissionGroupMethods<'a, C, NC, A> { + UserRolePermissionGroupMethods { hub: &self } + } + pub fn user_role_permissions(&'a self) -> UserRolePermissionMethods<'a, C, NC, A> { + UserRolePermissionMethods { hub: &self } + } + pub fn user_roles(&'a self) -> UserRoleMethods<'a, C, NC, A> { + UserRoleMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Operating System List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operating systems](struct.OperatingSystemListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperatingSystemsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystemsListResponse". + pub kind: String, + /// Operating system collection + #[serde(alias="operatingSystems")] + pub operating_systems: Vec, +} + +impl ResponseResult for OperatingSystemsListResponse {} + + +/// Directory Site Settings +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySiteSettings { + /// Whether this site accepts interstitial ads. + #[serde(alias="interstitialPlacementAccepted")] + pub interstitial_placement_accepted: bool, + /// Whether this directory site has disabled Nielsen OCR reach ratings. + #[serde(alias="nielsenOcrOptOut")] + pub nielsen_ocr_opt_out: bool, + /// Whether this directory site has disabled active view creatives. + #[serde(alias="activeViewOptOut")] + pub active_view_opt_out: bool, + /// Whether this directory site has disabled active view for in-stream video creatives. + #[serde(alias="videoActiveViewOptOut")] + pub video_active_view_opt_out: bool, + /// Directory site DFP settings. + pub dfp_settings: DfpSettings, + /// Whether this directory site has disabled generation of Verification tags. + #[serde(alias="verificationTagOptOut")] + pub verification_tag_opt_out: bool, + /// Whether this site accepts in-stream video ads. + pub instream_video_placement_accepted: bool, +} + +impl Part for DirectorySiteSettings {} + + +/// Contains information about a mobile carrier that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list mobile carriers](struct.MobileCarrierListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MobileCarrier { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#mobileCarrier". + pub kind: Option, + /// DART ID of the country to which this mobile carrier belongs. + #[serde(alias="countryDartId")] + pub country_dart_id: Option, + /// ID of this mobile carrier. + pub id: Option, + /// Country code of the country to which this mobile carrier belongs. + #[serde(alias="countryCode")] + pub country_code: Option, + /// Name of this mobile carrier. + pub name: Option, +} + +impl Resource for MobileCarrier {} + + +/// Contains properties of a DCM subaccount. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get subaccounts](struct.SubaccountGetCall.html) (response) +/// * [update subaccounts](struct.SubaccountUpdateCall.html) (request|response) +/// * [patch subaccounts](struct.SubaccountPatchCall.html) (request|response) +/// * [list subaccounts](struct.SubaccountListCall.html) (none) +/// * [insert subaccounts](struct.SubaccountInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Subaccount { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#subaccount". + pub kind: Option, + /// ID of the account that contains this subaccount. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// IDs of the available user role permissions for this subaccount. + #[serde(alias="availablePermissionIds")] + pub available_permission_ids: Option>, + /// ID of this subaccount. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this subaccount. This is a required field. Must be less than 128 characters long and be unique among subaccounts of the same account. + pub name: Option, +} + +impl RequestValue for Subaccount {} +impl Resource for Subaccount {} +impl ResponseResult for Subaccount {} + + +/// AccountPermissionGroups contains a mapping of permission group IDs to names. A permission group is a grouping of account permissions. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list account permission groups](struct.AccountPermissionGroupListCall.html) (none) +/// * [get account permission groups](struct.AccountPermissionGroupGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountPermissionGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionGroup". + pub kind: String, + /// ID of this account permission group. + pub id: String, + /// Name of this account permission group. + pub name: String, +} + +impl Resource for AccountPermissionGroup {} +impl ResponseResult for AccountPermissionGroup {} + + +/// Represents the list of DimensionValue resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query dimension values](struct.DimensionValueQueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DimensionValueList { + /// Continuation token used to page through dimension values. To retrieve the next page of results, set the next request's "pageToken" to the value of this field. The page token is only valid for a limited amount of time and should not be persisted. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The dimension values returned in this response. + pub items: Vec, + /// The kind of list this is, in this case dfareporting#dimensionValueList. + pub kind: String, + /// The eTag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for DimensionValueList {} + + +/// Campaign Creative Association List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list campaign creative associations](struct.CampaignCreativeAssociationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CampaignCreativeAssociationsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Campaign creative association collection + #[serde(alias="campaignCreativeAssociations")] + pub campaign_creative_associations: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignCreativeAssociationsListResponse". + pub kind: String, +} + +impl ResponseResult for CampaignCreativeAssociationsListResponse {} + + +/// Floodlight Activity List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list floodlight activities](struct.FloodlightActivityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FloodlightActivitiesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivitiesListResponse". + pub kind: String, + /// Floodlight activity collection + #[serde(alias="floodlightActivities")] + pub floodlight_activities: Vec, +} + +impl ResponseResult for FloodlightActivitiesListResponse {} + + +/// User Role Permission Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user role permission groups](struct.UserRolePermissionGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserRolePermissionGroupsListResponse { + /// User role permission group collection + #[serde(alias="userRolePermissionGroups")] + pub user_role_permission_groups: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionGroupsListResponse". + pub kind: String, +} + +impl ResponseResult for UserRolePermissionGroupsListResponse {} + + +/// Represents the list of File resources. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list files](struct.FileListCall.html) (response) +/// * [files list reports](struct.ReportFileListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FileList { + /// Continuation token used to page through files. To retrieve the next page of results, set the next request's "pageToken" to the value of this field. The page token is only valid for a limited amount of time and should not be persisted. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The files returned in this response. + pub items: Vec, + /// The kind of list this is, in this case dfareporting#fileList. + pub kind: String, + /// The eTag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for FileList {} + + +/// Represents a Custom Rich Media Events group. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomRichMediaEvents { + /// The kind of resource this is, in this case dfareporting#customRichMediaEvents. + pub kind: String, + /// List of custom rich media event IDs. Dimension values must be all of type dfa:richMediaEventTypeIdAndName. + #[serde(alias="filteredEventIds")] + pub filtered_event_ids: Vec, +} + +impl Part for CustomRichMediaEvents {} + + +/// Event tag override information. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventTagOverride { + /// Whether this override is enabled. + pub enabled: bool, + /// ID of this event tag override. This is a read-only, auto-generated field. + pub id: String, +} + +impl Part for EventTagOverride {} + + +/// Gets a summary of active ads in an account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get account active ad summaries](struct.AccountActiveAdSummaryGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountActiveAdSummary { + /// Ads that can be activated for the account. + #[serde(alias="availableAds")] + pub available_ads: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountActiveAdSummary". + pub kind: String, + /// ID of the account. + #[serde(alias="accountId")] + pub account_id: String, + /// Ads that have been activated for the account + #[serde(alias="activeAds")] + pub active_ads: String, + /// Maximum number of active ads allowed for the account. + #[serde(alias="activeAdsLimitTier")] + pub active_ads_limit_tier: String, +} + +impl ResponseResult for AccountActiveAdSummary {} + + +/// Lookback configuration settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LookbackConfiguration { + /// Lookback window, in days, from the last time a given user clicked on one of your ads. If you enter 0, clicks will not be considered as triggering events for floodlight tracking. If you leave this field blank, the default value for your account will be used. + #[serde(alias="clickDuration")] + pub click_duration: i32, + /// Lookback window, in days, from the last time a given user viewed one of your ads. If you enter 0, impressions will not be considered as triggering events for floodlight tracking. If you leave this field blank, the default value for your account will be used. + #[serde(alias="postImpressionActivitiesDuration")] + pub post_impression_activities_duration: i32, +} + +impl Part for LookbackConfiguration {} + + +/// Floodlight Activity GenerateTag Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generatetag floodlight activities](struct.FloodlightActivityGeneratetagCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FloodlightActivitiesGenerateTagResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivitiesGenerateTagResponse". + pub kind: String, + /// Generated tag for this floodlight activity. + #[serde(alias="floodlightActivityTag")] + pub floodlight_activity_tag: String, +} + +impl ResponseResult for FloodlightActivitiesGenerateTagResponse {} + + +/// Site Settings +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SiteSettings { + /// Whether brand safe ads are disabled for this site. + #[serde(alias="disableBrandSafeAds")] + pub disable_brand_safe_ads: bool, + /// Site-wide creative settings. + #[serde(alias="creativeSettings")] + pub creative_settings: CreativeSettings, + /// Whether active view creatives are disabled for this site. + #[serde(alias="activeViewOptOut")] + pub active_view_opt_out: bool, + /// Lookback window settings for this site. + #[serde(alias="lookbackConfiguration")] + pub lookback_configuration: LookbackConfiguration, + /// Whether new cookies are disabled for this site. + #[serde(alias="disableNewCookie")] + pub disable_new_cookie: bool, + /// Configuration settings for dynamic and image floodlight tags. + #[serde(alias="tagSetting")] + pub tag_setting: TagSetting, +} + +impl Part for SiteSettings {} + + +/// AccountUserProfiles contains properties of a DCM user profile. This resource is specifically for managing user profiles, whereas UserProfiles is for accessing the API. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch account user profiles](struct.AccountUserProfilePatchCall.html) (request|response) +/// * [list account user profiles](struct.AccountUserProfileListCall.html) (none) +/// * [get account user profiles](struct.AccountUserProfileGetCall.html) (response) +/// * [update account user profiles](struct.AccountUserProfileUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AccountUserProfile { + /// Locale of the user profile. This is a required field. + /// Acceptable values are: + /// - "cs" (Czech) + /// - "de" (German) + /// - "en" (English) + /// - "en-GB" (English United Kingdom) + /// - "es" (Spanish) + /// - "fr" (French) + /// - "it" (Italian) + /// - "ja" (Japanese) + /// - "ko" (Korean) + /// - "pl" (Polish) + /// - "pt-BR" (Portuguese Brazil) + /// - "ru" (Russian) + /// - "sv" (Swedish) + /// - "tr" (Turkish) + /// - "zh-CN" (Chinese Simplified) + /// - "zh-TW" (Chinese Traditional) + pub locale: Option, + /// Filter that describes which sites are visible to the user profile. + #[serde(alias="siteFilter")] + pub site_filter: Option, + /// Filter that describes which campaigns are visible to the user profile. + #[serde(alias="campaignFilter")] + pub campaign_filter: Option, + /// User role ID of the user profile. This is a required field. + #[serde(alias="userRoleId")] + pub user_role_id: Option, + /// User type of the user profile. This is a read-only field that can be left blank. + #[serde(alias="userAccessType")] + pub user_access_type: Option, + /// Whether this user profile is active. This defaults to false, and must be set true on insert for the user profile to be usable. + pub active: Option, + /// ID of the user profile. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of the user profile. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountUserProfile". + pub kind: Option, + /// Subaccount ID of the user profile. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Filter that describes which user roles are visible to the user profile. + #[serde(alias="userRoleFilter")] + pub user_role_filter: Option, + /// Trafficker type of this user profile. + #[serde(alias="traffickerType")] + pub trafficker_type: Option, + /// Comments for this user profile. + pub comments: Option, + /// Name of the user profile. This is a required field. Must be less than 64 characters long, must be globally unique, and cannot contain whitespace or any of the following characters: "&;"#%,". + pub name: Option, + /// Filter that describes which advertisers are visible to the user profile. + #[serde(alias="advertiserFilter")] + pub advertiser_filter: Option, + /// Email of the user profile. The email addresss must be linked to a Google Account. This field is required on insertion and is read-only after insertion. + pub email: Option, +} + +impl RequestValue for AccountUserProfile {} +impl Resource for AccountUserProfile {} +impl ResponseResult for AccountUserProfile {} + + +/// Dynamic and Image Tag Settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TagSettings { + /// Whether dynamic floodlight tags are enabled. + #[serde(alias="dynamicTagEnabled")] + pub dynamic_tag_enabled: bool, + /// Whether image tags are enabled. + #[serde(alias="imageTagEnabled")] + pub image_tag_enabled: bool, +} + +impl Part for TagSettings {} + + +/// Contains information about a particular version of an operating system that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operating system versions](struct.OperatingSystemVersionListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OperatingSystemVersion { + /// Major version (leftmost number) of this operating system version. + #[serde(alias="majorVersion")] + pub major_version: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystemVersion". + pub kind: Option, + /// Minor version (number after first dot on the left) of this operating system version. + #[serde(alias="minorVersion")] + pub minor_version: Option, + /// Name of this operating system version. + pub name: Option, + /// Operating system of this operating system version. + #[serde(alias="operatingSystem")] + pub operating_system: Option, + /// ID of this operating system version. + pub id: Option, +} + +impl Resource for OperatingSystemVersion {} + + +/// The properties of the report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportFloodlightCriteriaReportProperties { + /// Include conversions that have no associated cookies and no exposures. It’s therefore impossible to know how the user was exposed to your ads during the lookback window prior to a conversion. + #[serde(alias="includeUnattributedIPConversions")] + pub include_unattributed_ip_conversions: bool, + /// Include conversions of users with a DoubleClick cookie but without an exposure. That means the user did not click or see an ad from the advertiser within the Floodlight group, or that the interaction happened outside the lookback window. + #[serde(alias="includeUnattributedCookieConversions")] + pub include_unattributed_cookie_conversions: bool, + /// Include conversions that have no cookie, but do have an exposure path. + #[serde(alias="includeAttributedIPConversions")] + pub include_attributed_ip_conversions: bool, +} + +impl NestedType for ReportFloodlightCriteriaReportProperties {} +impl Part for ReportFloodlightCriteriaReportProperties {} + + +/// Creative Field Assignment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeFieldAssignment { + /// ID of the creative field. + #[serde(alias="creativeFieldId")] + pub creative_field_id: String, + /// ID of the creative field value. + #[serde(alias="creativeFieldValueId")] + pub creative_field_value_id: String, +} + +impl Part for CreativeFieldAssignment {} + + +/// Contains properties of a DCM account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update accounts](struct.AccountUpdateCall.html) (request|response) +/// * [list accounts](struct.AccountListCall.html) (none) +/// * [get accounts](struct.AccountGetCall.html) (response) +/// * [patch accounts](struct.AccountPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Account { + /// File size limit in kilobytes of Rich Media teaser creatives. Must be between 1 and 10240. + #[serde(alias="teaserSizeLimit")] + pub teaser_size_limit: Option, + /// Whether to serve creatives with Active View tags. If disabled, viewability data will not be available for any impressions. + #[serde(alias="activeViewOptOut")] + pub active_view_opt_out: Option, + /// Description of this account. + pub description: Option, + /// Locale of this account. + /// Acceptable values are: + /// - "cs" (Czech) + /// - "de" (German) + /// - "en" (English) + /// - "en-GB" (English United Kingdom) + /// - "es" (Spanish) + /// - "fr" (French) + /// - "it" (Italian) + /// - "ja" (Japanese) + /// - "ko" (Korean) + /// - "pl" (Polish) + /// - "pt-BR" (Portuguese Brazil) + /// - "ru" (Russian) + /// - "sv" (Swedish) + /// - "tr" (Turkish) + /// - "zh-CN" (Chinese Simplified) + /// - "zh-TW" (Chinese Traditional) + pub locale: Option, + /// Profile for this account. This is a read-only field that can be left blank. + #[serde(alias="accountProfile")] + pub account_profile: Option, + /// Whether this account is active. + pub active: Option, + /// Whether campaigns created in this account will be enabled for comScore vCE by default. + #[serde(alias="comscoreVceEnabled")] + pub comscore_vce_enabled: Option, + /// ID of this account. This is a read-only, auto-generated field. + pub id: Option, + /// User role permissions available to the user roles of this account. + #[serde(alias="availablePermissionIds")] + pub available_permission_ids: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#account". + pub kind: Option, + /// ID of the country associated with this account. + #[serde(alias="countryId")] + pub country_id: Option, + /// Name of this account. This is a required field, and must be less than 128 characters long and be globally unique. + pub name: Option, + /// Maximum image size allowed for this account. + #[serde(alias="maximumImageSize")] + pub maximum_image_size: Option, + /// Whether campaigns created in this account will be enabled for Nielsen OCR reach ratings by default. + #[serde(alias="nielsenOcrEnabled")] + pub nielsen_ocr_enabled: Option, + /// Default placement dimensions for this account. + #[serde(alias="defaultCreativeSizeId")] + pub default_creative_size_id: Option, + /// Account permissions assigned to this account. + #[serde(alias="accountPermissionIds")] + pub account_permission_ids: Option>, + /// ID of currency associated with this account. This is a required field. + /// Acceptable values are: + /// - "1" for USD + /// - "2" for GBP + /// - "3" for ESP + /// - "4" for SEK + /// - "5" for CAD + /// - "6" for JPY + /// - "7" for DEM + /// - "8" for AUD + /// - "9" for FRF + /// - "10" for ITL + /// - "11" for DKK + /// - "12" for NOK + /// - "13" for FIM + /// - "14" for ZAR + /// - "15" for IEP + /// - "16" for NLG + /// - "17" for EUR + /// - "18" for KRW + /// - "19" for TWD + /// - "20" for SGD + /// - "21" for CNY + /// - "22" for HKD + /// - "23" for NZD + /// - "24" for MYR + /// - "25" for BRL + /// - "26" for PTE + /// - "27" for MXP + /// - "28" for CLP + /// - "29" for TRY + /// - "30" for ARS + /// - "31" for PEN + /// - "32" for ILS + /// - "33" for CHF + /// - "34" for VEF + /// - "35" for COP + /// - "36" for GTQ + #[serde(alias="currencyId")] + pub currency_id: Option, + /// Reporting configuration of this account. + #[serde(alias="reportsConfiguration")] + pub reports_configuration: Option, + /// Maximum number of active ads allowed for this account. + #[serde(alias="activeAdsLimitTier")] + pub active_ads_limit_tier: Option, +} + +impl RequestValue for Account {} +impl Resource for Account {} +impl ResponseResult for Account {} + + +/// Day Part Targeting. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DayPartTargeting { + /// Days of the week when the ad will serve. + /// + /// Acceptable values are: + /// - "SUNDAY" + /// - "MONDAY" + /// - "TUESDAY" + /// - "WEDNESDAY" + /// - "THURSDAY" + /// - "FRIDAY" + /// - "SATURDAY" + #[serde(alias="daysOfWeek")] + pub days_of_week: Vec, + /// Hours of the day when the ad will serve. Must be an integer between 0 and 23 (inclusive), where 0 is midnight to 1 AM, and 23 is 11 PM to midnight. Can be specified with days of week, in which case the ad would serve during these hours on the specified days. For example, if Monday, Wednesday, Friday are the days of week specified and 9-10am, 3-5pm (hours 9, 15, and 16) is specified, the ad would serve Monday, Wednesdays, and Fridays at 9-10am and 3-5pm. + #[serde(alias="hoursOfDay")] + pub hours_of_day: Vec, + /// Whether or not to use the user's local time. If false, the America/New York time zone applies. + #[serde(alias="userLocalTime")] + pub user_local_time: bool, +} + +impl Part for DayPartTargeting {} + + +/// Represents a response to the queryCompatibleFields method. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [compatible fields query reports](struct.ReportCompatibleFieldQueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CompatibleFields { + /// The kind of resource this is, in this case dfareporting#compatibleFields. + pub kind: String, + /// Contains items that are compatible to be selected for a report of type "CROSS_DIMENSION_REACH". + #[serde(alias="crossDimensionReachReportCompatibleFields")] + pub cross_dimension_reach_report_compatible_fields: CrossDimensionReachReportCompatibleFields, + /// Contains items that are compatible to be selected for a report of type "REACH". + #[serde(alias="reachReportCompatibleFields")] + pub reach_report_compatible_fields: ReachReportCompatibleFields, + /// Contains items that are compatible to be selected for a report of type "PATH_TO_CONVERSION". + #[serde(alias="pathToConversionReportCompatibleFields")] + pub path_to_conversion_report_compatible_fields: PathToConversionReportCompatibleFields, + /// Contains items that are compatible to be selected for a report of type "FLOODLIGHT". + #[serde(alias="floodlightReportCompatibleFields")] + pub floodlight_report_compatible_fields: FloodlightReportCompatibleFields, + /// Contains items that are compatible to be selected for a report of type "STANDARD". + #[serde(alias="reportCompatibleFields")] + pub report_compatible_fields: ReportCompatibleFields, +} + +impl ResponseResult for CompatibleFields {} + + +/// Contains information about a region that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list regions](struct.RegionListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Region { + /// Region code. + #[serde(alias="regionCode")] + pub region_code: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#region". + pub kind: Option, + /// DART ID of the country to which this region belongs. + #[serde(alias="countryDartId")] + pub country_dart_id: Option, + /// Name of this region. + pub name: Option, + /// Country code of the country to which this region belongs. + #[serde(alias="countryCode")] + pub country_code: Option, + /// DART ID of this region. + #[serde(alias="dartId")] + pub dart_id: Option, +} + +impl Resource for Region {} + + +/// The report criteria for a report of type "STANDARD". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportCriteria { + /// Activity group. + pub activities: Activities, + /// The list of standard dimensions the report should include. + pub dimensions: Vec, + /// The list of names of metrics the report should include. + #[serde(alias="metricNames")] + pub metric_names: Vec, + /// The date range for which this report should be run. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// Custom Rich Media Events group. + #[serde(alias="customRichMediaEvents")] + pub custom_rich_media_events: CustomRichMediaEvents, + /// The list of filters on which dimensions are filtered. + /// Filters for different dimensions are ANDed, filters for the same dimension are grouped together and ORed. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, +} + +impl NestedType for ReportCriteria {} +impl Part for ReportCriteria {} + + +/// Represents fields that are compatible to be selected for a report of type "CROSS_DIMENSION_REACH". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CrossDimensionReachReportCompatibleFields { + /// Dimensions which are compatible to be selected in the "breakdown" section of the report. + pub breakdown: Vec, + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Vec, + /// The kind of resource this is, in this case dfareporting#crossDimensionReachReportCompatibleFields. + pub kind: String, + /// Metrics which are compatible to be selected in the "overlapMetricNames" section of the report. + #[serde(alias="overlapMetrics")] + pub overlap_metrics: Vec, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, +} + +impl Part for CrossDimensionReachReportCompatibleFields {} + + +/// Contains properties of auser role, which is used to manage user access. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert user roles](struct.UserRoleInsertCall.html) (request|response) +/// * [update user roles](struct.UserRoleUpdateCall.html) (request|response) +/// * [delete user roles](struct.UserRoleDeleteCall.html) (none) +/// * [patch user roles](struct.UserRolePatchCall.html) (request|response) +/// * [list user roles](struct.UserRoleListCall.html) (none) +/// * [get user roles](struct.UserRoleGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserRole { + /// Whether this is a default user role. Default user roles are created by the system for the account/subaccount and cannot be modified or deleted. Each default user role comes with a basic set of preassigned permissions. + #[serde(alias="defaultUserRole")] + pub default_user_role: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRole". + pub kind: Option, + /// Subaccount ID of this user role. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this user role. This is a required field. Must be less than 256 characters long. If this user role is under a subaccount, the name must be unique among sites of the same subaccount. Otherwise, this user role is a top-level user role, and the name must be unique among top-level user roles of the same account. + pub name: Option, + /// ID of the user role that this user role is based on or copied from. This is a required field. + #[serde(alias="parentUserRoleId")] + pub parent_user_role_id: Option, + /// Account ID of this user role. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// ID of this user role. This is a read-only, auto-generated field. + pub id: Option, + /// List of permissions associated with this user role. + pub permissions: Option>, +} + +impl RequestValue for UserRole {} +impl Resource for UserRole {} +impl ResponseResult for UserRole {} + + +/// Event Tag List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list event tags](struct.EventTagListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct EventTagsListResponse { + /// Event tag collection + #[serde(alias="eventTags")] + pub event_tags: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#eventTagsListResponse". + pub kind: String, +} + +impl ResponseResult for EventTagsListResponse {} + + +/// Contains properties of a Floodlight activity group. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get floodlight activity groups](struct.FloodlightActivityGroupGetCall.html) (response) +/// * [patch floodlight activity groups](struct.FloodlightActivityGroupPatchCall.html) (request|response) +/// * [update floodlight activity groups](struct.FloodlightActivityGroupUpdateCall.html) (request|response) +/// * [list floodlight activity groups](struct.FloodlightActivityGroupListCall.html) (none) +/// * [delete floodlight activity groups](struct.FloodlightActivityGroupDeleteCall.html) (none) +/// * [insert floodlight activity groups](struct.FloodlightActivityGroupInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FloodlightActivityGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivityGroup". + pub kind: Option, + /// Subaccount ID of this floodlight activity group. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this floodlight activity group. This is a required field. Must be less than 65 characters long and cannot contain quotes. + pub name: Option, + /// Floodlight configuration ID of this floodlight activity group. This is a required field. + #[serde(alias="floodlightConfigurationId")] + pub floodlight_configuration_id: Option, + /// Advertiser ID of this floodlight activity group. If this field is left blank, the value will be copied over either from the floodlight configuration's advertiser or from the existing activity group's advertiser. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(alias="floodlightConfigurationIdDimensionValue")] + pub floodlight_configuration_id_dimension_value: Option, + /// Dimension value for the ID of this floodlight activity group. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Value of the type= parameter in the floodlight tag, which the ad servers use to identify the activity group that the activity belongs to. This is optional: if empty, a new tag string will be generated for you. This string must be 1 to 8 characters long, with valid characters being [a-z][A-Z][0-9][-][ _ ]. This tag string must also be unique among activity groups of the same floodlight configuration. This field is read-only after insertion. + #[serde(alias="tagString")] + pub tag_string: Option, + /// Type of the floodlight activity group. This is a required field that is read-only after insertion. + #[serde(alias="type")] + pub type_: Option, + /// ID of this floodlight activity group. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this floodlight activity group. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for FloodlightActivityGroup {} +impl Resource for FloodlightActivityGroup {} +impl ResponseResult for FloodlightActivityGroup {} + + +/// Audience Segment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AudienceSegment { + /// Weight allocated to this segment. Must be between 1 and 1000. The weight assigned will be understood in proportion to the weights assigned to other segments in the same segment group. + pub allocation: i32, + /// ID of this audience segment. This is a read-only, auto-generated field. + pub id: String, + /// Name of this audience segment. This is a required field and must be less than 65 characters long. + pub name: String, +} + +impl Part for AudienceSegment {} + + +/// Contains properties of a DCM campaign. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert campaigns](struct.CampaignInsertCall.html) (request|response) +/// * [update campaigns](struct.CampaignUpdateCall.html) (request|response) +/// * [patch campaigns](struct.CampaignPatchCall.html) (request|response) +/// * [get campaigns](struct.CampaignGetCall.html) (response) +/// * [list campaigns](struct.CampaignListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Campaign { + /// Arbitrary comments about this campaign. Must be less than 256 characters long. + pub comment: Option, + /// Date on which the campaign starts running. The start date can be any date. The hours, minutes, and seconds of the start date should not be set, as doing so will result in an error. This is a required field. + #[serde(alias="startDate")] + pub start_date: Option, + /// Date on which the campaign will stop running. On insert, the end date must be today or a future date. The end date must be later than or be the same as the start date. If, for example, you set 6/25/2015 as both the start and end dates, the effective campaign run date is just that day only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so will result in an error. This is a required field. + #[serde(alias="endDate")] + pub end_date: Option, + /// Click-through URL suffix override properties for this campaign. + #[serde(alias="clickThroughUrlSuffixProperties")] + pub click_through_url_suffix_properties: Option, + /// Whether this campaign has been archived. + pub archived: Option, + /// Additional creative optimization configurations for the campaign. + #[serde(alias="additionalCreativeOptimizationConfigurations")] + pub additional_creative_optimization_configurations: Option>, + /// Advertiser ID of this campaign. This is a required field. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Audience segment groups assigned to this campaign. Cannot have more than 300 segment groups. + #[serde(alias="audienceSegmentGroups")] + pub audience_segment_groups: Option>, + /// Information about the creation of this campaign. This is a read-only field. + #[serde(alias="createInfo")] + pub create_info: Option, + /// Click-through event tag ID override properties for this campaign. + #[serde(alias="defaultClickThroughEventTagProperties")] + pub default_click_through_event_tag_properties: Option, + /// Dimension value for the advertiser ID of this campaign. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Overrides that can be used to activate or deactivate advertiser event tags. + #[serde(alias="eventTagOverrides")] + pub event_tag_overrides: Option>, + /// Creative optimization configuration for the campaign. + #[serde(alias="creativeOptimizationConfiguration")] + pub creative_optimization_configuration: Option, + /// ID of this campaign. This is a read-only auto-generated field. + pub id: Option, + /// Account ID of this campaign. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Campaign trafficker contact emails. + #[serde(alias="traffickerEmails")] + pub trafficker_emails: Option>, + /// List of creative group IDs that are assigned to the campaign. + #[serde(alias="creativeGroupIds")] + pub creative_group_ids: Option>, + /// Subaccount ID of this campaign. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this campaign. This is a required field and must be less than 256 characters long and unique among campaigns of the same advertiser. + pub name: Option, + /// Lookback window settings for the campaign. + #[serde(alias="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Whether Nielsen reports are enabled for this campaign. + #[serde(alias="nielsenOcrEnabled")] + pub nielsen_ocr_enabled: Option, + /// Information about the most recent modification of this campaign. This is a read-only field. + #[serde(alias="lastModifiedInfo")] + pub last_modified_info: Option, + /// Whether comScore vCE reports are enabled for this campaign. + #[serde(alias="comscoreVceEnabled")] + pub comscore_vce_enabled: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaign". + pub kind: Option, + /// External ID for this campaign. + #[serde(alias="externalId")] + pub external_id: Option, + /// Advertiser group ID of the associated advertiser. + #[serde(alias="advertiserGroupId")] + pub advertiser_group_id: Option, + /// Dimension value for the ID of this campaign. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Billing invoice code included in the DCM client billing invoices associated with the campaign. + #[serde(alias="billingInvoiceCode")] + pub billing_invoice_code: Option, +} + +impl RequestValue for Campaign {} +impl Resource for Campaign {} +impl ResponseResult for Campaign {} + + +/// Describes a change that a user has made to a resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list change logs](struct.ChangeLogListCall.html) (none) +/// * [get change logs](struct.ChangeLogGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChangeLog { + /// Time when the object was modified. + #[serde(alias="changeTime")] + pub change_time: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#changeLog". + pub kind: String, + /// Subaccount ID of the modified object. + #[serde(alias="subaccountId")] + pub subaccount_id: String, + /// Old value of the object field. + #[serde(alias="oldValue")] + pub old_value: String, + /// ID of the object of this change log. The object could be a campaign, placement, ad, or other type. + #[serde(alias="objectId")] + pub object_id: String, + /// ID of this change log. + pub id: String, + /// User profile name of the user who modified the object. + #[serde(alias="userProfileName")] + pub user_profile_name: String, + /// Field name of the object which changed. + #[serde(alias="fieldName")] + pub field_name: String, + /// ID of the user who modified the object. + #[serde(alias="userProfileId")] + pub user_profile_id: String, + /// Action which caused the change. + pub action: String, + /// Transaction ID of this change log. When a single API call results in many changes, each change will have a separate ID in the change log but will share the same transactionId. + #[serde(alias="transactionId")] + pub transaction_id: String, + /// Account ID of the modified object. + #[serde(alias="accountId")] + pub account_id: String, + /// New value of the object field. + #[serde(alias="newValue")] + pub new_value: String, + /// Object type of the change log. + #[serde(alias="objectType")] + pub object_type: String, +} + +impl Resource for ChangeLog {} +impl ResponseResult for ChangeLog {} + + +/// Represents a File resource. A file contains the metadata for a report run. It shows the status of the run and holds the URLs to the generated report data if the run is finished and the status is "REPORT_AVAILABLE". +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get files](struct.FileGetCall.html) (response) +/// * [list files](struct.FileListCall.html) (none) +/// * [files get reports](struct.ReportFileGetCall.html) (response) +/// * [run reports](struct.ReportRunCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct File { + /// The status of the report file. + pub status: String, + /// The kind of resource this is, in this case dfareporting#file. + pub kind: String, + /// The output format of the report. Only available once the file is available. + pub format: String, + /// The date range for which the file has report data. The date range will always be the absolute date range for which the report is run. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// The filename of the file. + #[serde(alias="fileName")] + pub file_name: String, + /// The eTag of this response for caching purposes. + pub etag: String, + /// The ID of the report this file was generated from. + #[serde(alias="reportId")] + pub report_id: String, + /// The URLs where the completed report file can be downloaded. + pub urls: FileUrls, + /// The timestamp in milliseconds since epoch when this file was last modified. + #[serde(alias="lastModifiedTime")] + pub last_modified_time: String, + /// The unique ID of this report file. + pub id: String, +} + +impl Resource for File {} +impl ResponseResult for File {} + + +/// Key Value Targeting Expression. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct KeyValueTargetingExpression { + /// Keyword expression being targeted by the ad. + pub expression: String, +} + +impl Part for KeyValueTargetingExpression {} + + +/// The report criteria for a report of type "CROSS_DIMENSION_REACH". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportCrossDimensionReachCriteria { + /// The list of dimensions the report should include. + pub breakdown: Vec, + /// Whether the report is pivoted or not. Defaults to true. + pub pivoted: bool, + /// The list of names of overlap metrics the report should include. + #[serde(alias="overlapMetricNames")] + pub overlap_metric_names: Vec, + /// The list of names of metrics the report should include. + #[serde(alias="metricNames")] + pub metric_names: Vec, + /// The date range this report should be run for. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// The list of filters on which dimensions are filtered. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, + /// The dimension option. + pub dimension: String, +} + +impl NestedType for ReportCrossDimensionReachCriteria {} +impl Part for ReportCrossDimensionReachCriteria {} + + +/// Audience Segment Group. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AudienceSegmentGroup { + /// Audience segments assigned to this group. The number of segments must be between 2 and 100. + #[serde(alias="audienceSegments")] + pub audience_segments: Vec, + /// ID of this audience segment group. This is a read-only, auto-generated field. + pub id: String, + /// Name of this audience segment group. This is a required field and must be less than 65 characters long. + pub name: String, +} + +impl Part for AudienceSegmentGroup {} + + +/// Contains properties of a placement strategy. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch placement strategies](struct.PlacementStrategyPatchCall.html) (request|response) +/// * [insert placement strategies](struct.PlacementStrategyInsertCall.html) (request|response) +/// * [get placement strategies](struct.PlacementStrategyGetCall.html) (response) +/// * [update placement strategies](struct.PlacementStrategyUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PlacementStrategy { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementStrategy". + pub kind: Option, + /// Account ID of this placement strategy.This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// ID of this placement strategy. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this placement strategy. This is a required field. Must be less than 256 characters long and unique among placement strategies of the same account. + pub name: Option, +} + +impl RequestValue for PlacementStrategy {} +impl ResponseResult for PlacementStrategy {} + + +/// Placement Tag +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlacementTag { + /// Tags generated for this placement. + #[serde(alias="tagDatas")] + pub tag_datas: Vec, + /// Placement ID + #[serde(alias="placementId")] + pub placement_id: String, +} + +impl Part for PlacementTag {} + + +/// Country List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list countries](struct.CountryListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CountriesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#countriesListResponse". + pub kind: String, + /// Country collection + pub countries: Vec, +} + +impl ResponseResult for CountriesListResponse {} + + +/// Click-through URL +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ClickThroughUrl { + /// ID of the landing page for the click-through URL. Applicable if the defaultLandingPage field is set to false. + #[serde(alias="landingPageId")] + pub landing_page_id: String, + /// Custom click-through URL. Applicable if the defaultLandingPage field is set to false and the landingPageId field is left unset. + #[serde(alias="customClickThroughUrl")] + pub custom_click_through_url: String, + /// Whether the campaign default landing page is used. + #[serde(alias="defaultLandingPage")] + pub default_landing_page: bool, +} + +impl Part for ClickThroughUrl {} + + +/// Companion Click-through override. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CompanionClickThroughOverride { + /// Click-through URL of this companion click-through override. + #[serde(alias="clickThroughUrl")] + pub click_through_url: ClickThroughUrl, + /// ID of the creative for this companion click-through override. + #[serde(alias="creativeId")] + pub creative_id: String, +} + +impl Part for CompanionClickThroughOverride {} + + +/// Frequency Cap. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FrequencyCap { + /// Duration of time, in seconds, for this frequency cap. The maximum duration is 90 days in seconds, or 7,776,000. + pub duration: String, + /// Number of times an individual user can be served the ad within the specified duration. The maximum allowed is 15. + pub impressions: String, +} + +impl Part for FrequencyCap {} + + +/// Identifies a creative which has been associated with a given campaign. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list campaign creative associations](struct.CampaignCreativeAssociationListCall.html) (none) +/// * [insert campaign creative associations](struct.CampaignCreativeAssociationInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CampaignCreativeAssociation { + /// ID of the creative associated with the campaign. This is a required field. + #[serde(alias="creativeId")] + pub creative_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignCreativeAssociation". + pub kind: Option, +} + +impl RequestValue for CampaignCreativeAssociation {} +impl Resource for CampaignCreativeAssociation {} +impl ResponseResult for CampaignCreativeAssociation {} + + +/// Operating System Version List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operating system versions](struct.OperatingSystemVersionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct OperatingSystemVersionsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystemVersionsListResponse". + pub kind: String, + /// Operating system version collection + #[serde(alias="operatingSystemVersions")] + pub operating_system_versions: Vec, +} + +impl ResponseResult for OperatingSystemVersionsListResponse {} + + +/// Organizes placements according to the contents of their associated webpages. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch content categories](struct.ContentCategoryPatchCall.html) (request|response) +/// * [insert content categories](struct.ContentCategoryInsertCall.html) (request|response) +/// * [update content categories](struct.ContentCategoryUpdateCall.html) (request|response) +/// * [get content categories](struct.ContentCategoryGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ContentCategory { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#contentCategory". + pub kind: Option, + /// Account ID of this content category. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Description of this content category. + pub description: Option, + /// Name of this content category. This is a required field and must be less than 256 characters long and unique among content categories of the same account. + pub name: Option, + /// ID of this content category. This is a read-only, auto-generated field. + pub id: Option, +} + +impl RequestValue for ContentCategory {} +impl ResponseResult for ContentCategory {} + + +/// Contains properties of a placement. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generatetags placements](struct.PlacementGeneratetagCall.html) (none) +/// * [insert placements](struct.PlacementInsertCall.html) (request|response) +/// * [update placements](struct.PlacementUpdateCall.html) (request|response) +/// * [list placements](struct.PlacementListCall.html) (none) +/// * [get placements](struct.PlacementGetCall.html) (response) +/// * [patch placements](struct.PlacementPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Placement { + /// Comments for this placement. + pub comment: Option, + /// Campaign ID of this placement. This field is a required field on insertion. + #[serde(alias="campaignId")] + pub campaign_id: Option, + /// Payment source for this placement. This is a required field that is read-only after insertion. + #[serde(alias="paymentSource")] + pub payment_source: Option, + /// Dimension value for the ID of the directory site. This is a read-only, auto-generated field. + #[serde(alias="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Advertiser ID of this placement. This field can be left blank. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Key name of this placement. This is a read-only, auto-generated field. + #[serde(alias="keyName")] + pub key_name: Option, + /// Directory site ID of this placement. On insert, you must set either this field or the siteId field to specify the site associated with this placement. This is a required field that is read-only after insertion. + #[serde(alias="directorySiteId")] + pub directory_site_id: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of the content category assigned to this placement. + #[serde(alias="contentCategoryId")] + pub content_category_id: Option, + /// Size associated with this placement. When inserting or updating a placement, only the size ID field is used. This field is required on insertion. + pub size: Option, + /// Whether this placement is archived. + pub archived: Option, + /// Information about the last publisher update. This is a read-only field. + #[serde(alias="publisherUpdateInfo")] + pub publisher_update_info: Option, + /// Tag formats to generate for this placement. This field is required on insertion. + /// Acceptable values are: + /// - "PLACEMENT_TAG_STANDARD" + /// - "PLACEMENT_TAG_IFRAME_JAVASCRIPT" + /// - "PLACEMENT_TAG_IFRAME_ILAYER" + /// - "PLACEMENT_TAG_INTERNAL_REDIRECT" + /// - "PLACEMENT_TAG_JAVASCRIPT" + /// - "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" + /// - "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" + /// - "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" + /// - "PLACEMENT_TAG_CLICK_COMMANDS" + /// - "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" + /// - "PLACEMENT_TAG_TRACKING" + /// - "PLACEMENT_TAG_TRACKING_IFRAME" + /// - "PLACEMENT_TAG_TRACKING_JAVASCRIPT" + #[serde(alias="tagFormats")] + pub tag_formats: Option>, + /// Whether payment was approved for this placement. This is a read-only field relevant only to publisher-paid placements. + #[serde(alias="paymentApproved")] + pub payment_approved: Option, + /// Tag settings for this placement. + #[serde(alias="tagSetting")] + pub tag_setting: Option, + /// ID of this placement. This is a read-only, auto-generated field. + pub id: Option, + /// External ID for this placement. + #[serde(alias="externalId")] + pub external_id: Option, + /// Dimension value for the ID of this placement. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Account ID of this placement. This field can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Whether creatives assigned to this placement must be SSL-compliant. + #[serde(alias="sslRequired")] + pub ssl_required: Option, + /// Third-party placement status. + pub status: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(alias="campaignIdDimensionValue")] + pub campaign_id_dimension_value: Option, + /// Whether this placement is the primary placement of a roadblock (placement group). You cannot change this field from true to false. Setting this field to true will automatically set the primary field on the original primary placement of the roadblock to false, and it will automatically set the roadblock's primaryPlacementId field to the ID of this placement. + pub primary: Option, + /// ID of this placement's group, if applicable. + #[serde(alias="placementGroupId")] + pub placement_group_id: Option, + /// Information about the creation of this placement. This is a read-only field. + #[serde(alias="createInfo")] + pub create_info: Option, + /// Site ID associated with this placement. On insert, you must set either this field or the directorySiteId field to specify the site associated with this placement. This is a required field that is read-only after insertion. + #[serde(alias="siteId")] + pub site_id: Option, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(alias="siteIdDimensionValue")] + pub site_id_dimension_value: Option, + /// Placement compatibility. WEB and WEB_INTERSTITIAL refer to rendering either on desktop or on mobile devices for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are for rendering in mobile apps.IN_STREAM_VIDEO refers to rendering in in-stream video ads developed with the VAST standard. This field is required on insertion. + pub compatibility: Option, + /// ID of the placement strategy assigned to this placement. + #[serde(alias="placementStrategyId")] + pub placement_strategy_id: Option, + /// Dimension value for the ID of the placement group. This is a read-only, auto-generated field. + #[serde(alias="placementGroupIdDimensionValue")] + pub placement_group_id_dimension_value: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placement". + pub kind: Option, + /// Subaccount ID of this placement. This field can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this placement.This is a required field and must be less than 256 characters long. + pub name: Option, + /// Lookback window settings for this placement. + #[serde(alias="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Information about the most recent modification of this placement. This is a read-only field. + #[serde(alias="lastModifiedInfo")] + pub last_modified_info: Option, + /// Pricing schedule of this placement. This field is required on insertion, specifically subfields startDate, endDate and pricingType. + #[serde(alias="pricingSchedule")] + pub pricing_schedule: Option, +} + +impl RequestValue for Placement {} +impl Resource for Placement {} +impl ResponseResult for Placement {} + + +/// Represents fields that are compatible to be selected for a report of type "FlOODLIGHT". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FloodlightReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Vec, + /// The kind of resource this is, in this case dfareporting#floodlightReportCompatibleFields. + pub kind: String, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Vec, +} + +impl Part for FloodlightReportCompatibleFields {} + + +/// Creative Asset ID. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeAssetId { + /// Type of asset to upload. This is a required field. IMAGE is solely used for IMAGE creatives. Other image assets should use HTML_IMAGE. + #[serde(alias="type")] + pub type_: String, + /// Name of the creative asset. This is a required field while inserting an asset. After insertion, this assetIdentifier is used to identify the uploaded asset. Characters in the name must be alphanumeric or one of the following: ".-_ ". Spaces are allowed. + pub name: String, +} + +impl Part for CreativeAssetId {} + + +/// Directory Site Contact Assignment +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySiteContactAssignment { + /// ID of this directory site contact. This is a read-only, auto-generated field. + #[serde(alias="contactId")] + pub contact_id: String, + /// Visibility of this directory site contact assignment. When set to PUBLIC this contact assignment is visible to all account and agency users; when set to PRIVATE it is visible only to the site. + pub visibility: String, +} + +impl Part for DirectorySiteContactAssignment {} + + +/// Creative Assignment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeAssignment { + /// Weight of the creative assignment, applicable when the rotation type is CREATIVE_ROTATION_TYPE_RANDOM. + pub weight: i32, + /// Sequence number of the creative assignment, applicable when the rotation type is CREATIVE_ROTATION_TYPE_SEQUENTIAL. + pub sequence: i32, + /// Click-through URL of the creative assignment. + #[serde(alias="clickThroughUrl")] + pub click_through_url: ClickThroughUrl, + /// Rich media exit overrides for this creative assignment. + /// Applicable when the creative type is any of the following: + /// - RICH_MEDIA_INPAGE + /// - RICH_MEDIA_INPAGE_FLOATING + /// - RICH_MEDIA_IM_EXPAND + /// - RICH_MEDIA_EXPANDING + /// - RICH_MEDIA_INTERSTITIAL_FLOAT + /// - RICH_MEDIA_MOBILE_IN_APP + /// - RICH_MEDIA_MULTI_FLOATING + /// - RICH_MEDIA_PEEL_DOWN + /// - ADVANCED_BANNER + /// - VPAID_LINEAR + /// - VPAID_NON_LINEAR + #[serde(alias="richMediaExitOverrides")] + pub rich_media_exit_overrides: Vec, + /// Whether applicable event tags should fire when this creative assignment is rendered. If this value is unset when the ad is inserted or updated, it will default to true for all creative types EXCEPT for INTERNAL_REDIRECT, INTERSTITIAL_INTERNAL_REDIRECT, and INSTREAM_VIDEO. + #[serde(alias="applyEventTags")] + pub apply_event_tags: bool, + /// Creative group assignments for this creative assignment. Only one assignment per creative group number is allowed for a maximum of two assignments. + #[serde(alias="creativeGroupAssignments")] + pub creative_group_assignments: Vec, + /// Companion creative overrides for this creative assignment. Applicable to video ads. + #[serde(alias="companionCreativeOverrides")] + pub companion_creative_overrides: Vec, + /// Date and time that the assigned creative should start serving. + #[serde(alias="startTime")] + pub start_time: String, + /// Whether the creative to be assigned is SSL-compliant. This is a read-only field that is auto-generated when the ad is inserted or updated. + #[serde(alias="sslCompliant")] + pub ssl_compliant: bool, + /// Whether this creative assignment is active. When true, the creative will be included in the ad's rotation. + pub active: bool, + /// ID of the creative to be assigned. This is a required field. + #[serde(alias="creativeId")] + pub creative_id: String, + /// Date and time that the assigned creative should stop serving. Must be later than the start time. + #[serde(alias="endTime")] + pub end_time: String, + /// Dimension value for the ID of the creative. This is a read-only, auto-generated field. + #[serde(alias="creativeIdDimensionValue")] + pub creative_id_dimension_value: DimensionValue, +} + +impl Part for CreativeAssignment {} + + +/// Represents a DimensionValuesRequest. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query dimension values](struct.DimensionValueQueryCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DimensionValueRequest { + /// The name of the dimension for which values should be requested. + #[serde(alias="dimensionName")] + pub dimension_name: Option, + /// The start date of the date range for which to retrieve dimension values. A string of the format "yyyy-MM-dd". + #[serde(alias="startDate")] + pub start_date: Option, + /// The kind of request this is, in this case dfareporting#dimensionValueRequest. + pub kind: Option, + /// The end date of the date range for which to retrieve dimension values. A string of the format "yyyy-MM-dd". + #[serde(alias="endDate")] + pub end_date: Option, + /// The list of filters by which to filter values. The filters are ANDed. + pub filters: Option>, +} + +impl RequestValue for DimensionValueRequest {} + + +/// Properties of inheriting and overriding the default click-through event tag. A campaign may override the event tag defined at the advertiser level, and an ad may also override the campaign's setting further. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DefaultClickThroughEventTagProperties { + /// Whether this entity should override the inherited default click-through event tag with its own defined value. + #[serde(alias="overrideInheritedEventTag")] + pub override_inherited_event_tag: bool, + /// ID of the click-through event tag to apply to all ads in this entity's scope. + #[serde(alias="defaultClickThroughEventTagId")] + pub default_click_through_event_tag_id: String, +} + +impl Part for DefaultClickThroughEventTagProperties {} + + +/// Represents the list of user profiles. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user profiles](struct.UserProfileListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserProfileList { + /// The user profiles returned in this response. + pub items: Vec, + /// The kind of list this is, in this case dfareporting#userProfileList. + pub kind: String, + /// The eTag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for UserProfileList {} + + +/// Subaccount List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list subaccounts](struct.SubaccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SubaccountsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#subaccountsListResponse". + pub kind: String, + /// Subaccount collection + pub subaccounts: Vec, +} + +impl ResponseResult for SubaccountsListResponse {} + + +/// Represents a Report resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [run reports](struct.ReportRunCall.html) (none) +/// * [get reports](struct.ReportGetCall.html) (response) +/// * [list reports](struct.ReportListCall.html) (none) +/// * [delete reports](struct.ReportDeleteCall.html) (none) +/// * [files list reports](struct.ReportFileListCall.html) (none) +/// * [insert reports](struct.ReportInsertCall.html) (request|response) +/// * [patch reports](struct.ReportPatchCall.html) (request|response) +/// * [compatible fields query reports](struct.ReportCompatibleFieldQueryCall.html) (request) +/// * [update reports](struct.ReportUpdateCall.html) (request|response) +/// * [files get reports](struct.ReportFileGetCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Report { + /// The user profile id of the owner of this report. + #[serde(alias="ownerProfileId")] + pub owner_profile_id: Option, + /// The subaccount ID to which this report belongs if applicable. + #[serde(alias="subAccountId")] + pub sub_account_id: Option, + /// The report's schedule. Can only be set if the report's 'dateRange' is a relative date range and the relative date range is not "TODAY". + pub schedule: Option, + /// The report criteria for a report of type "PATH_TO_CONVERSION". + #[serde(alias="pathToConversionCriteria")] + pub path_to_conversion_criteria: Option, + /// The report criteria for a report of type "REACH". + #[serde(alias="reachCriteria")] + pub reach_criteria: Option, + /// The report criteria for a report of type "FLOODLIGHT". + #[serde(alias="floodlightCriteria")] + pub floodlight_criteria: Option, + /// The filename used when generating report files for this report. + #[serde(alias="fileName")] + pub file_name: Option, + /// The report's email delivery settings. + pub delivery: Option, + /// The timestamp (in milliseconds since epoch) of when this report was last modified. + #[serde(alias="lastModifiedTime")] + pub last_modified_time: Option, + /// The report criteria for a report of type "CROSS_DIMENSION_REACH". + #[serde(alias="crossDimensionReachCriteria")] + pub cross_dimension_reach_criteria: Option, + /// The account ID to which this report belongs. + #[serde(alias="accountId")] + pub account_id: Option, + /// The kind of resource this is, in this case dfareporting#report. + pub kind: Option, + /// The name of the report. + pub name: Option, + /// The output format of the report. If not specified, default format is "CSV". Note that the actual format in the completed report file might differ if for instance the report's size exceeds the format's capabilities. "CSV" will then be the fallback format. + pub format: Option, + /// The unique ID identifying this report resource. + pub id: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, + /// The report criteria for a report of type "STANDARD". + pub criteria: Option, + /// The type of the report. + #[serde(alias="type")] + pub type_: Option, +} + +impl RequestValue for Report {} +impl Resource for Report {} +impl ResponseResult for Report {} + + +/// Contains information about a platform type that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list platform types](struct.PlatformTypeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PlatformType { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#platformType". + pub kind: Option, + /// ID of this platform type. + pub id: Option, + /// Name of this platform type. + pub name: Option, +} + +impl Resource for PlatformType {} + + +/// Advertiser List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list advertisers](struct.AdvertiserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdvertisersListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Advertiser collection + pub advertisers: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertisersListResponse". + pub kind: String, +} + +impl ResponseResult for AdvertisersListResponse {} + + +/// Creative Asset. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert creative assets](struct.CreativeAssetInsertCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeAsset { + /// Detected MIME type for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="mimeType")] + pub mime_type: Option, + /// Artwork type of rich media creative. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="artworkType")] + pub artwork_type: Option, + /// Offset left unit for an asset. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="positionLeftUnit")] + pub position_left_unit: Option, + /// Size of an asset when collapsed. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA and all VPAID. Additionally, applicable to assets whose displayType is ASSET_DISPLAY_TYPE_EXPANDING or ASSET_DISPLAY_TYPE_PEEL_DOWN. + #[serde(alias="collapsedSize")] + pub collapsed_size: Option, + /// Flash version of the asset. This is a read-only field. Applicable to the following creative types: FLASH_INPAGE, ENHANCED_BANNER, all RICH_MEDIA, and all VPAID. + #[serde(alias="flashVersion")] + pub flash_version: Option, + /// Whether the asset pushes down other content. Applicable to the following creative types: all RICH_MEDIA. Additionally, only applicable when the asset offsets are 0, the collapsedSize.width matches size.width, and the collapsedSize.height is less than size.height. + pub pushdown: Option, + /// Whether to hide Flash objects flag for an asset. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="hideFlashObjects")] + pub hide_flash_objects: Option, + /// List of feature dependencies for the creative asset that are detected by DCM. Feature dependencies are features that a browser must be able to support in order to render your HTML5 creative correctly. This is a read-only, auto-generated field. Applicable to the following creative types: ENHANCED_BANNER and HTML5_BANNER. + #[serde(alias="detectedFeatures")] + pub detected_features: Option>, + /// Duration in seconds for which an asset will be displayed. Applicable to the following creative types: INSTREAM_VIDEO and VPAID_LINEAR. + pub duration: Option, + /// Offset top unit for an asset. This is a read-only field if the asset displayType is ASSET_DISPLAY_TYPE_OVERLAY. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="positionTopUnit")] + pub position_top_unit: Option, + /// Numeric ID of this creative asset. This is a required field and should not be modified. Applicable to all but the following creative types: all REDIRECT and TRACKING_TEXT. + pub id: Option, + /// Possible alignments for an asset. This is a read-only field. Applicable to the following creative types: RICH_MEDIA_MULTI_FLOATING. + pub alignment: Option, + /// Size associated with this creative asset. This is a required field when applicable; however for IMAGE and FLASH_INPAGE creatives, if left blank, this field will be automatically set using the actual size of the associated image asset. Applicable to the following creative types: ENHANCED_BANNER, ENHANCED_IMAGE, FLASH_INPAGE, HTML5_BANNER, IMAGE, and all RICH_MEDIA. + pub size: Option, + /// Whether the asset is horizontally locked. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="horizontallyLocked")] + pub horizontally_locked: Option, + /// Initial wait time type before making the asset visible. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="startTimeType")] + pub start_time_type: Option, + /// Type of rich media asset. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="displayType")] + pub display_type: Option, + /// Detected expanded dimension for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="expandedDimension")] + pub expanded_dimension: Option, + /// Whether the asset is vertically locked. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="verticallyLocked")] + pub vertically_locked: Option, + /// Role of the asset in relation to creative. Applicable to all but the following creative types: all REDIRECT and TRACKING_TEXT. This is a required field. + /// PRIMARY applies to ENHANCED_BANNER, FLASH_INPAGE, HTML5_BANNER, IMAGE, IMAGE_GALLERY, all RICH_MEDIA (which may contain multiple primary assets), and all VPAID creatives. + /// BACKUP_IMAGE applies to ENHANCED_BANNER, FLASH_INPAGE, HTML5_BANNER, all RICH_MEDIA, and all VPAID creatives. + /// ADDITIONAL_IMAGE and ADDITIONAL_FLASH apply to FLASH_INPAGE creatives. + /// OTHER refers to assets from sources other than DCM, such as Studio uploaded assets, applicable to all RICH_MEDIA and all VPAID creatives. + /// PARENT_VIDEO refers to videos uploaded by the user in DCM and is applicable to INSTREAM_VIDEO and VPAID_LINEAR creatives. + /// TRANSCODED_VIDEO refers to videos transcoded by DCM from PARENT_VIDEO assets and is applicable to INSTREAM_VIDEO and VPAID_LINEAR creatives. + /// ALTERNATE_VIDEO refers to the DCM representation of child asset videos from Studio, and is applicable to VPAID_LINEAR creatives. These cannot be added or removed within DCM. + /// For VPAID_LINEAR creatives, PARENT_VIDEO, TRANSCODED_VIDEO and ALTERNATE_VIDEO assets that are marked active serve as backup in case the VPAID creative cannot be served. Only PARENT_VIDEO assets can be added or removed for an INSTREAM_VIDEO or VPAID_LINEAR creative. + pub role: Option, + /// Size of zip file. This is a read-only field. Applicable to the following creative types: HTML5_BANNER. + #[serde(alias="zipFilesize")] + pub zip_filesize: Option, + /// Detected bit-rate for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="bitRate")] + pub bit_rate: Option, + /// Window mode options for flash assets. Applicable to the following creative types: FLASH_INPAGE, RICH_MEDIA_EXPANDING, RICH_MEDIA_IM_EXPAND, RICH_MEDIA_INPAGE, and RICH_MEDIA_INPAGE_FLOATING. + #[serde(alias="windowMode")] + pub window_mode: Option, + /// Progressive URL for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="progressiveServingUrl")] + pub progressive_serving_url: Option, + /// Duration type for which an asset will be displayed. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="durationType")] + pub duration_type: Option, + /// Detected video duration for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="videoDuration")] + pub video_duration: Option, + /// File size associated with this creative asset. This is a read-only field. Applicable to all but the following creative types: all REDIRECT and TRACKING_TEXT. + #[serde(alias="fileSize")] + pub file_size: Option, + /// Offset position for an asset in collapsed mode. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA and all VPAID. Additionally, only applicable to assets whose displayType is ASSET_DISPLAY_TYPE_EXPANDING or ASSET_DISPLAY_TYPE_PEEL_DOWN. + pub offset: Option, + /// Whether the video asset is active. This is a read-only field for VPAID_NON_LINEAR assets. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + pub active: Option, + /// Whether the backup asset is original or changed by the user in DCM. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="originalBackup")] + pub original_backup: Option, + /// Whether to hide selection boxes flag for an asset. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="hideSelectionBoxes")] + pub hide_selection_boxes: Option, + /// Streaming URL for video asset. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="streamingServingUrl")] + pub streaming_serving_url: Option, + /// zIndex value of an asset. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA.Additionally, only applicable to assets whose displayType is NOT one of the following types: ASSET_DISPLAY_TYPE_INPAGE or ASSET_DISPLAY_TYPE_OVERLAY. + #[serde(alias="zIndex")] + pub z_index: Option, + /// Rich media child asset type. This is a read-only field. Applicable to the following creative types: all VPAID. + #[serde(alias="childAssetType")] + pub child_asset_type: Option, + /// Exit event configured for the backup image. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="backupImageExit")] + pub backup_image_exit: Option, + /// Whether ActionScript3 is enabled for the flash asset. This is a read-only field. Applicable to the following creative types: FLASH_INPAGE and ENHANCED_BANNER. + #[serde(alias="actionScript3")] + pub action_script3: Option, + /// Pushdown duration in seconds for an asset. Must be between 0 and 9.99. Applicable to the following creative types: all RICH_MEDIA.Additionally, only applicable when the asset pushdown field is true, the offsets are 0, the collapsedSize.width matches size.width, and the collapsedSize.height is less than size.height. + #[serde(alias="pushdownDuration")] + pub pushdown_duration: Option, + /// Identifier of this asset. This is the same identifier returned during creative asset insert operation. This is a required field. Applicable to all but the following creative types: all REDIRECT and TRACKING_TEXT. + #[serde(alias="assetIdentifier")] + pub asset_identifier: Option, + /// Whether the asset is transparent. Applicable to the following creative types: all RICH_MEDIA. Additionally, only applicable to HTML5 assets. + pub transparency: Option, + /// Whether the asset is SSL-compliant. This is a read-only field. Applicable to all but the following creative types: all REDIRECT and TRACKING_TEXT. + #[serde(alias="sslCompliant")] + pub ssl_compliant: Option, + /// Offset position for an asset. Applicable to the following creative types: all RICH_MEDIA. + pub position: Option, + /// Custom start time in seconds for making the asset visible. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="customStartTimeValue")] + pub custom_start_time_value: Option, + /// File name of zip file. This is a read-only field. Applicable to the following creative types: HTML5_BANNER. + #[serde(alias="zipFilename")] + pub zip_filename: Option, +} + +impl Resource for CreativeAsset {} + + +/// Directory Site List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list directory sites](struct.DirectorySiteListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySitesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySitesListResponse". + pub kind: String, + /// Directory site collection + #[serde(alias="directorySites")] + pub directory_sites: Vec, +} + +impl ResponseResult for DirectorySitesListResponse {} + + +/// Modification timestamp. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LastModifiedInfo { + /// Timestamp of the last change in milliseconds since epoch. + pub time: String, +} + +impl Part for LastModifiedInfo {} + + +/// Region List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list regions](struct.RegionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RegionsListResponse { + /// Region Collection. + pub regions: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#regionsListResponse". + pub kind: String, +} + +impl ResponseResult for RegionsListResponse {} + + +/// Represents a grouping of related user role permissions. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user role permission groups](struct.UserRolePermissionGroupListCall.html) (none) +/// * [get user role permission groups](struct.UserRolePermissionGroupGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserRolePermissionGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionGroup". + pub kind: String, + /// ID of this user role permission. + pub id: String, + /// Name of this user role permission group. + pub name: String, +} + +impl Resource for UserRolePermissionGroup {} +impl ResponseResult for UserRolePermissionGroup {} + + +/// Creative Click Tag. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ClickTag { + /// Advertiser event name associated with the click tag. This field is used by ENHANCED_BANNER, ENHANCED_IMAGE, and HTML5_BANNER creatives. + #[serde(alias="eventName")] + pub event_name: String, + /// Parameter name for the specified click tag. For ENHANCED_IMAGE creative assets, this field must match the value of the creative asset's creativeAssetId.name field. + pub name: String, + /// Parameter value for the specified click tag. This field contains a click-through url. + pub value: String, +} + +impl Part for ClickTag {} + + +/// Contains information about a connection type that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list connection types](struct.ConnectionTypeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ConnectionType { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#connectionType". + pub kind: Option, + /// ID of this connection type. + pub id: Option, + /// Name of this connection type. + pub name: Option, +} + +impl Resource for ConnectionType {} + + +/// Browser List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list browsers](struct.BrowserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct BrowsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#browsersListResponse". + pub kind: String, + /// Browser collection + pub browsers: Vec, +} + +impl ResponseResult for BrowsersListResponse {} + + +/// Object Filter. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ObjectFilter { + /// Applicable when status is ASSIGNED. The user has access to objects with these object IDs. + #[serde(alias="objectIds")] + pub object_ids: Vec, + /// Status of the filter. NONE means the user has access to none of the objects. ALL means the user has access to all objects. ASSIGNED means the user has access to the objects with IDs in the objectIds list. + pub status: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#objectFilter". + pub kind: String, +} + +impl Part for ObjectFilter {} + + +/// Creative Settings +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeSettings { + /// Header text for iFrames for this site. Must be less than or equal to 2000 characters long. + #[serde(alias="iFrameHeader")] + pub i_frame_header: String, + /// Header text for iFrames for this site. Must be less than or equal to 2000 characters long. + #[serde(alias="iFrameFooter")] + pub i_frame_footer: String, +} + +impl Part for CreativeSettings {} + + +/// Represents a dimension. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Dimension { + /// The kind of resource this is, in this case dfareporting#dimension. + pub kind: String, + /// The dimension name, e.g. dfa:advertiser + pub name: String, +} + +impl Part for Dimension {} + + +/// Contains properties of a creative field. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creative fields](struct.CreativeFieldListCall.html) (none) +/// * [update creative fields](struct.CreativeFieldUpdateCall.html) (request|response) +/// * [get creative fields](struct.CreativeFieldGetCall.html) (response) +/// * [insert creative fields](struct.CreativeFieldInsertCall.html) (request|response) +/// * [delete creative fields](struct.CreativeFieldDeleteCall.html) (none) +/// * [patch creative fields](struct.CreativeFieldPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeField { + /// Advertiser ID of this creative field. This is a required field on insertion. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeField". + pub kind: Option, + /// Subaccount ID of this creative field. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this creative field. This is a required field and must be less than 256 characters long and unique among creative fields of the same advertiser. + pub name: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of this creative field. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this creative field. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for CreativeField {} +impl Resource for CreativeField {} +impl ResponseResult for CreativeField {} + + +/// DirectorySites contains properties of a website from the Site Directory. Sites need to be added to an account via the Sites resource before they can be assigned to a placement. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get directory sites](struct.DirectorySiteGetCall.html) (response) +/// * [list directory sites](struct.DirectorySiteListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySite { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySite". + pub kind: String, + /// Country ID of this directory site. + #[serde(alias="countryId")] + pub country_id: String, + /// Description of this directory site. + pub description: String, + /// Directory site settings. + pub settings: DirectorySiteSettings, + /// Currency ID of this directory site. + /// Possible values are: + /// - "1" for USD + /// - "2" for GBP + /// - "3" for ESP + /// - "4" for SEK + /// - "5" for CAD + /// - "6" for JPY + /// - "7" for DEM + /// - "8" for AUD + /// - "9" for FRF + /// - "10" for ITL + /// - "11" for DKK + /// - "12" for NOK + /// - "13" for FIM + /// - "14" for ZAR + /// - "15" for IEP + /// - "16" for NLG + /// - "17" for EUR + /// - "18" for KRW + /// - "19" for TWD + /// - "20" for SGD + /// - "21" for CNY + /// - "22" for HKD + /// - "23" for NZD + /// - "24" for MYR + /// - "25" for BRL + /// - "26" for PTE + /// - "27" for MXP + /// - "28" for CLP + /// - "29" for TRY + /// - "30" for ARS + /// - "31" for PEN + /// - "32" for ILS + /// - "33" for CHF + /// - "34" for VEF + /// - "35" for COP + /// - "36" for GTQ + #[serde(alias="currencyId")] + pub currency_id: String, + /// Tag types for regular placements. + /// + /// Acceptable values are: + /// - "STANDARD" + /// - "IFRAME_JAVASCRIPT_INPAGE" + /// - "INTERNAL_REDIRECT_INPAGE" + /// - "JAVASCRIPT_INPAGE" + #[serde(alias="inpageTagFormats")] + pub inpage_tag_formats: Vec, + /// URL of this directory site. + pub url: String, + /// Directory site contacts. + #[serde(alias="contactAssignments")] + pub contact_assignments: Vec, + /// Parent directory site ID. + #[serde(alias="parentId")] + pub parent_id: String, + /// Tag types for interstitial placements. + /// + /// Acceptable values are: + /// - "IFRAME_JAVASCRIPT_INTERSTITIAL" + /// - "INTERNAL_REDIRECT_INTERSTITIAL" + /// - "JAVASCRIPT_INTERSTITIAL" + #[serde(alias="interstitialTagFormats")] + pub interstitial_tag_formats: Vec, + /// Dimension value for the ID of this directory site. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: DimensionValue, + /// Whether this directory site is active. + pub active: bool, + /// ID of this directory site. This is a read-only, auto-generated field. + pub id: String, + /// Name of this directory site. + pub name: String, +} + +impl Resource for DirectorySite {} +impl ResponseResult for DirectorySite {} + + +/// City List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list cities](struct.CityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CitiesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#citiesListResponse". + pub kind: String, + /// City collection + pub cities: Vec, +} + +impl ResponseResult for CitiesListResponse {} + + +/// Contains properties of a creative group. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get creative groups](struct.CreativeGroupGetCall.html) (response) +/// * [update creative groups](struct.CreativeGroupUpdateCall.html) (request|response) +/// * [patch creative groups](struct.CreativeGroupPatchCall.html) (request|response) +/// * [list creative groups](struct.CreativeGroupListCall.html) (none) +/// * [insert creative groups](struct.CreativeGroupInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeGroup". + pub kind: Option, + /// Subaccount ID of this creative group. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this creative group. This is a required field and must be less than 256 characters long and unique among creative groups of the same advertiser. + pub name: Option, + /// Subgroup of the creative group. Assign your creative groups to one of the following subgroups in order to filter or manage them more easily. This field is required on insertion and is read-only after insertion. + /// Acceptable values are: + /// - 1 + /// - 2 + #[serde(alias="groupNumber")] + pub group_number: Option, + /// Advertiser ID of this creative group. This is a required field on insertion. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of this creative group. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this creative group. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for CreativeGroup {} +impl Resource for CreativeGroup {} +impl ResponseResult for CreativeGroup {} + + +/// Represents a metric. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Metric { + /// The kind of resource this is, in this case dfareporting#metric. + pub kind: String, + /// The metric name, e.g. dfa:impressions + pub name: String, +} + +impl Part for Metric {} + + +/// Rich Media Exit Override. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RichMediaExitOverride { + /// Click-through URL to override the default exit URL. Applicable if the useCustomExitUrl field is set to true. + #[serde(alias="customExitUrl")] + pub custom_exit_url: String, + /// Whether to use the custom exit URL. + #[serde(alias="useCustomExitUrl")] + pub use_custom_exit_url: bool, + /// ID for the override to refer to a specific exit in the creative. + #[serde(alias="exitId")] + pub exit_id: String, +} + +impl Part for RichMediaExitOverride {} + + +/// Account Permission List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list account permissions](struct.AccountPermissionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountPermissionsListResponse { + /// Account permission collection + #[serde(alias="accountPermissions")] + pub account_permissions: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionsListResponse". + pub kind: String, +} + +impl ResponseResult for AccountPermissionsListResponse {} + + +/// Placement GenerateTags Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generatetags placements](struct.PlacementGeneratetagCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlacementsGenerateTagsResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementsGenerateTagsResponse". + pub kind: String, + /// Set of generated tags for the specified placements. + #[serde(alias="placementTags")] + pub placement_tags: Vec, +} + +impl ResponseResult for PlacementsGenerateTagsResponse {} + + +/// Contains properties of a creative field value. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert creative field values](struct.CreativeFieldValueInsertCall.html) (request|response) +/// * [get creative field values](struct.CreativeFieldValueGetCall.html) (response) +/// * [update creative field values](struct.CreativeFieldValueUpdateCall.html) (request|response) +/// * [patch creative field values](struct.CreativeFieldValuePatchCall.html) (request|response) +/// * [list creative field values](struct.CreativeFieldValueListCall.html) (none) +/// * [delete creative field values](struct.CreativeFieldValueDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeFieldValue { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeFieldValue". + pub kind: Option, + /// ID of this creative field value. This is a read-only, auto-generated field. + pub id: Option, + /// Value of this creative field value. It needs to be less than 256 characters in length and unique per creative field. + pub value: Option, +} + +impl RequestValue for CreativeFieldValue {} +impl Resource for CreativeFieldValue {} +impl ResponseResult for CreativeFieldValue {} + + +/// Floodlight Activity Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list floodlight activity groups](struct.FloodlightActivityGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FloodlightActivityGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivityGroupsListResponse". + pub kind: String, + /// Floodlight activity group collection + #[serde(alias="floodlightActivityGroups")] + pub floodlight_activity_groups: Vec, +} + +impl ResponseResult for FloodlightActivityGroupsListResponse {} + + +/// Directory Site Contact List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list directory site contacts](struct.DirectorySiteContactListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySiteContactsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Directory site contact collection + #[serde(alias="directorySiteContacts")] + pub directory_site_contacts: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySiteContactsListResponse". + pub kind: String, +} + +impl ResponseResult for DirectorySiteContactsListResponse {} + + +/// Creative Custom Event. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeCustomEvent { + /// Target type used by the event. + #[serde(alias="targetType")] + pub target_type: String, + /// Artwork type used by the creative.This is a read-only field. + #[serde(alias="artworkType")] + pub artwork_type: String, + /// Reporting ID, used to differentiate multiple videos in a single creative. + #[serde(alias="videoReportingId")] + pub video_reporting_id: String, + /// Properties for rich media popup windows. This field is used only for exit events. + #[serde(alias="popupWindowProperties")] + pub popup_window_properties: PopupWindowProperties, + /// Artwork label column, used to link events in DCM back to events in Studio. This is a required field and should not be modified after insertion. + #[serde(alias="artworkLabel")] + pub artwork_label: String, + /// Whether the event is active. + pub active: bool, + /// Type of the event. This is a read-only field. + #[serde(alias="advertiserCustomEventType")] + pub advertiser_custom_event_type: String, + /// Exit URL of the event. This field is used only for exit events. + #[serde(alias="exitUrl")] + pub exit_url: String, + /// ID of this event. This is a required field and should not be modified after insertion. + pub id: String, + /// User-entered name for the event. + #[serde(alias="advertiserCustomEventName")] + pub advertiser_custom_event_name: String, +} + +impl Part for CreativeCustomEvent {} + + +/// Creative List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creatives](struct.CreativeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CreativesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativesListResponse". + pub kind: String, + /// Creative collection + pub creatives: Vec, +} + +impl ResponseResult for CreativesListResponse {} + + +/// Omniture Integration Settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OmnitureSettings { + /// Whether placement cost data will be sent to Omniture. This property can be enabled only if omnitureIntegrationEnabled is true. + #[serde(alias="omnitureCostDataEnabled")] + pub omniture_cost_data_enabled: bool, + /// Whether Omniture integration is enabled. This property can be enabled only when the "Advanced Ad Serving" account setting is enabled. + #[serde(alias="omnitureIntegrationEnabled")] + pub omniture_integration_enabled: bool, +} + +impl Part for OmnitureSettings {} + + +/// Represents fields that are compatible to be selected for a report of type "PATH_TO_CONVERSION". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PathToConversionReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Vec, + /// Per-interaction dimensions which are compatible to be selected in the "perInteractionDimensions" section of the report. + #[serde(alias="perInteractionDimensions")] + pub per_interaction_dimensions: Vec, + /// The kind of resource this is, in this case dfareporting#pathToConversionReportCompatibleFields. + pub kind: String, + /// Conversion dimensions which are compatible to be selected in the "conversionDimensions" section of the report. + #[serde(alias="conversionDimensions")] + pub conversion_dimensions: Vec, + /// Custom floodlight variables which are compatible to be selected in the "customFloodlightVariables" section of the report. + #[serde(alias="customFloodlightVariables")] + pub custom_floodlight_variables: Vec, +} + +impl Part for PathToConversionReportCompatibleFields {} + + +/// Mobile Carrier List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list mobile carriers](struct.MobileCarrierListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MobileCarriersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#mobileCarriersListResponse". + pub kind: String, + /// Mobile carrier collection + #[serde(alias="mobileCarriers")] + pub mobile_carriers: Vec, +} + +impl ResponseResult for MobileCarriersListResponse {} + + +/// Dynamic Tag +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FloodlightActivityDynamicTag { + /// Tag code. + pub tag: String, + /// ID of this dynamic tag. This is a read-only, auto-generated field. + pub id: String, + /// Name of this tag. + pub name: String, +} + +impl Part for FloodlightActivityDynamicTag {} + + +/// Contains properties of a Creative. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert creatives](struct.CreativeInsertCall.html) (request|response) +/// * [get creatives](struct.CreativeGetCall.html) (response) +/// * [list creatives](struct.CreativeListCall.html) (none) +/// * [update creatives](struct.CreativeUpdateCall.html) (request|response) +/// * [patch creatives](struct.CreativePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Creative { + /// Type of artwork used for the creative. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="artworkType")] + pub artwork_type: Option, + /// Latest Studio trafficked creative ID associated with rich media and VPAID creatives. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="latestTraffickedCreativeId")] + pub latest_trafficked_creative_id: Option, + /// List of counter events configured for the creative. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="counterCustomEvents")] + pub counter_custom_events: Option>, + /// Advertiser ID of this creative. This is a required field. Applicable to all creative types. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Whether the creative is active. Applicable to all creative types. + pub active: Option, + /// List of timer events configured for the creative. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="timerCustomEvents")] + pub timer_custom_events: Option>, + /// Dimension value for the rendering ID of this creative. This is a read-only field. Applicable to all creative types. + #[serde(alias="renderingIdDimensionValue")] + pub rendering_id_dimension_value: Option, + /// OpenWindow FSCommand of this creative. This lets the SWF file communicate with either Flash Player or the program hosting Flash Player, such as a web browser. This is only triggered if allowScriptAccess field is true. Applicable to the following creative types: FLASH_INPAGE. + #[serde(alias="fsCommand")] + pub fs_command: Option, + /// ID of this creative. This is a read-only, auto-generated field. Applicable to all creative types. + pub id: Option, + /// Account ID of this creative. This field, if left unset, will be auto-generated for both insert and update operations. Applicable to all creative types. + #[serde(alias="accountId")] + pub account_id: Option, + /// Studio trafficked creative ID associated with rich media and VPAID creatives. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="studioTraffickedCreativeId")] + pub studio_trafficked_creative_id: Option, + /// Whether the creative is archived. Applicable to all creative types. + pub archived: Option, + /// Override CSS value for rich media creatives. Applicable to the following creative types: all RICH_MEDIA. + #[serde(alias="overrideCss")] + pub override_css: Option, + /// Whether script access is allowed for this creative. This is a read-only and deprecated field which will automatically be set to true on update. Applicable to the following creative types: FLASH_INPAGE. + #[serde(alias="allowScriptAccess")] + pub allow_script_access: Option, + /// The internal Flash version for this creative as calculated by DoubleClick Studio. This is a read-only field. Applicable to the following creative types: FLASH_INPAGE, ENHANCED_BANNER, all RICH_MEDIA, and all VPAID. + #[serde(alias="requiredFlashVersion")] + pub required_flash_version: Option, + /// List of exit events configured for the creative. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="exitCustomEvents")] + pub exit_custom_events: Option>, + /// ID of current rendering version. This is a read-only field. Applicable to all creative types. + #[serde(alias="renderingId")] + pub rendering_id: Option, + /// Description of the video ad. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="videoDescription")] + pub video_description: Option, + /// Third-party URL used to record backup image impressions. Applicable to the following creative types: all RICH_MEDIA + #[serde(alias="thirdPartyBackupImageImpressionsUrl")] + pub third_party_backup_image_impressions_url: Option, + /// The version number helps you keep track of multiple versions of your creative in your reports. The version number will always be auto-generated during insert operations to start at 1. For tracking creatives the version cannot be incremented and will always remain at 1. For all other creative types the version can be incremented only by 1 during update operations. In addition, the version will be automatically incremented by 1 when undergoing Rich Media creative merging. Applicable to all creative types. + pub version: Option, + /// Creative field assignments for this creative. Applicable to all creative types. + #[serde(alias="creativeFieldAssignments")] + pub creative_field_assignments: Option>, + /// The 6-character HTML color code, beginning with #, for the background of the window area where the Flash file is displayed. Default is white. Applicable to the following creative types: FLASH_INPAGE. + #[serde(alias="backgroundColor")] + pub background_color: Option, + /// Custom key-values for a Rich Media creative. Key-values let you customize the creative settings of a Rich Media ad running on your site without having to contact the advertiser. You can use key-values to dynamically change the look or functionality of a creative. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="customKeyValues")] + pub custom_key_values: Option>, + /// Dimension value for the ID of this creative. This is a read-only field. Applicable to all creative types. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Whether images are automatically advanced for enhanced image creatives. Applicable to the following creative types: ENHANCED_IMAGE. + pub auto_advance_images: Option, + /// Size associated with this creative. When inserting or updating a creative either the size ID field or size width and height fields can be used. This is a required field when applicable; however for IMAGE and FLASH_INPAGE creatives, if left blank, this field will be automatically set using the actual size of the associated image assets. Applicable to the following creative types: ENHANCED_BANNER, ENHANCED_IMAGE, FLASH_INPAGE, HTML5_BANNER, IMAGE, and all RICH_MEDIA. + pub size: Option, + /// Type of this creative.This is a required field. Applicable to all creative types. + #[serde(alias="type")] + pub type_: Option, + /// Combined size of all creative assets. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="totalFileSize")] + pub total_file_size: Option, + /// Third-party URL used to record rich media impressions. Applicable to the following creative types: all RICH_MEDIA + #[serde(alias="thirdPartyRichMediaImpressionsUrl")] + pub third_party_rich_media_impressions_url: Option, + /// Studio advertiser ID associated with rich media and VPAID creatives. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="studioAdvertiserId")] + pub studio_advertiser_id: Option, + /// Assets associated with a creative. Applicable to all but the following creative types: INTERNAL_REDIRECT, INTERSTITIAL_INTERNAL_REDIRECT, and REDIRECT + #[serde(alias="creativeAssets")] + pub creative_assets: Option>, + /// List of feature dependencies that will cause a backup image to be served if the browser that serves the ad does not support them. Feature dependencies are features that a browser must be able to support in order to render your HTML5 creative asset correctly. This field is initially auto-generated to contain all features detected by DCM for all the assets of this creative and can then be modified by the client. To reset this field, copy over all the creativeAssets' detected features. Applicable to the following creative types: ENHANCED_BANNER and HTML5_BANNER. + #[serde(alias="backupImageFeatures")] + pub backup_image_features: Option>, + /// Whether HTML code is DCM-generated or manually entered. Set to true to ignore changes to htmlCode. Applicable to the following creative types: FLASH_INPAGE and HTML5_BANNER. + #[serde(alias="htmlCodeLocked")] + pub html_code_locked: Option, + /// URL of hosted image or another ad tag. This is a required field when applicable. Applicable to the following creative types: INTERNAL_REDIRECT, INTERSTITIAL_INTERNAL_REDIRECT, and REDIRECT + #[serde(alias="redirectUrl")] + pub redirect_url: Option, + /// Click tags of the creative. For ENHANCED_BANNER, FLASH_INPAGE, and HTML5_BANNER creatives, this is a subset of detected click tags for the assets associated with this creative. After creating a flash asset, detected click tags will be returned in the creativeAssetMetadata. When inserting the creative, populate the creative clickTags field using the creativeAssetMetadata.clickTags field. For ENHANCED_IMAGE creatives, there should be exactly one entry in this list for each image creative asset. A click tag is matched with a corresponding creative asset by matching the clickTag.name field with the creativeAsset.assetIdentifier.name field. Applicable to the following creative types: ENHANCED_BANNER, ENHANCED_IMAGE, FLASH_INPAGE, HTML5_BANNER. + #[serde(alias="clickTags")] + pub click_tags: Option>, + /// Target window for backup image. Applicable to the following creative types: ENHANCED_BANNER, FLASH_INPAGE, and HTML5_BANNER. + #[serde(alias="backupImageTargetWindow")] + pub backup_image_target_window: Option, + /// The minimum required Flash plugin version for this creative. For example, 11.2.202.235. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="requiredFlashPluginVersion")] + pub required_flash_plugin_version: Option, + /// Reporting label used for HTML5 banner backup image. Applicable to the following creative types: ENHANCED_BANNER. + #[serde(alias="backupImageReportingLabel")] + pub backup_image_reporting_label: Option, + /// Compatibilities associated with this creative. This is a read-only field. WEB and WEB_INTERSTITIAL refer to rendering either on desktop or on mobile devices for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are for rendering in mobile apps. IN_STREAM_VIDEO refers to rendering in in-stream video ads developed with the VAST standard. Applicable to all creative types. + /// + /// Acceptable values are: + /// - "APP" + /// - "APP_INTERSTITIAL" + /// - "IN_STREAM_VIDEO" + /// - "WEB" + /// - "WEB_INTERSTITIAL" + pub compatibility: Option>, + /// Ad parameters user for VPAID creative. This is a read-only field. Applicable to the following creative types: all VPAID. + #[serde(alias="adParameters")] + pub ad_parameters: Option, + /// Keywords for a Rich Media creative. Keywords let you customize the creative settings of a Rich Media ad running on your site without having to contact the advertiser. You can use keywords to dynamically change the look or functionality of a creative. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="adTagKeys")] + pub ad_tag_keys: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creative". + pub kind: Option, + /// Subaccount ID of this creative. This field, if left unset, will be auto-generated for both insert and update operations. Applicable to all creative types. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of the creative. This is a required field and must be less than 256 characters long. Applicable to all creative types. + pub name: Option, + /// Creative video duration in seconds. This is a read-only field. Applicable to the following creative types: INSTREAM_VIDEO, all RICH_MEDIA, and all VPAID. + #[serde(alias="videoDuration")] + pub video_duration: Option, + /// Creative last modification information. This is a read-only field. Applicable to all creative types. + #[serde(alias="lastModifiedInfo")] + pub last_modified_info: Option, + /// Click-through URL for backup image. Applicable to the following creative types: ENHANCED_BANNER, FLASH_INPAGE, and HTML5_BANNER. + #[serde(alias="backupImageClickThroughUrl")] + pub backup_image_click_through_url: Option, + /// Studio creative ID associated with rich media and VPAID creatives. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA, and all VPAID. + #[serde(alias="studioCreativeId")] + pub studio_creative_id: Option, + /// Authoring tool for HTML5 banner creatives. This is a read-only field. Applicable to the following creative types: HTML5_BANNER. + #[serde(alias="authoringTool")] + pub authoring_tool: Option, + /// Third-party URLs for tracking in-stream video creative events. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="thirdPartyUrls")] + pub third_party_urls: Option>, + /// List of companion creatives assigned to an in-Stream videocreative. Acceptable values include IDs of existing flash and image creatives. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="companionCreatives")] + pub companion_creatives: Option>, + /// HTML code for the creative. This is a required field when applicable. This field is ignored if htmlCodeLocked is false. Applicable to the following creative types: all CUSTOM, FLASH_INPAGE, and HTML5_BANNER, and all RICH_MEDIA. + #[serde(alias="htmlCode")] + pub html_code: Option, + /// Whether the creative is SSL-compliant. This is a read-only field. Applicable to all creative types. + #[serde(alias="sslCompliant")] + pub ssl_compliant: Option, + /// Industry standard ID assigned to creative for reach and frequency. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(alias="commercialId")] + pub commercial_id: Option, + /// Whether the user can choose to skip the creative. Applicable to the following creative types: INSTREAM_VIDEO. + pub skippable: Option, +} + +impl RequestValue for Creative {} +impl Resource for Creative {} +impl ResponseResult for Creative {} + + +/// Reporting Configuration +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportsConfiguration { + /// Whether the exposure to conversion report is enabled. This report shows detailed pathway information on up to 10 of the most recent ad exposures seen by a user before converting. + #[serde(alias="exposureToConversionEnabled")] + pub exposure_to_conversion_enabled: bool, + /// Report generation time zone ID of this account. This is a required field that can only be changed by a superuser. + /// Acceptable values are: + /// + /// - "1" for "America/New_York" + /// - "2" for "Europe/London" + /// - "3" for "Europe/Paris" + /// - "4" for "Africa/Johannesburg" + /// - "5" for "Asia/Jerusalem" + /// - "6" for "Asia/Shanghai" + /// - "7" for "Asia/Hong_Kong" + /// - "8" for "Asia/Tokyo" + /// - "9" for "Australia/Sydney" + /// - "10" for "Asia/Dubai" + /// - "11" for "America/Los_Angeles" + /// - "12" for "Pacific/Auckland" + /// - "13" for "America/Sao_Paulo" + #[serde(alias="reportGenerationTimeZoneId")] + pub report_generation_time_zone_id: String, + /// Default lookback windows for new advertisers in this account. + #[serde(alias="lookbackConfiguration")] + pub lookback_configuration: LookbackConfiguration, +} + +impl Part for ReportsConfiguration {} + + +/// Campaign List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list campaigns](struct.CampaignListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CampaignsListResponse { + /// Campaign collection + pub campaigns: Vec, + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignsListResponse". + pub kind: String, +} + +impl ResponseResult for CampaignsListResponse {} + + +/// User Role Permission List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user role permissions](struct.UserRolePermissionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserRolePermissionsListResponse { + /// User role permission collection + #[serde(alias="userRolePermissions")] + pub user_role_permissions: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionsListResponse". + pub kind: String, +} + +impl ResponseResult for UserRolePermissionsListResponse {} + + +/// Represents a UserProfile resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user profiles](struct.UserProfileListCall.html) (none) +/// * [get user profiles](struct.UserProfileGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserProfile { + /// The user name. + #[serde(alias="userName")] + pub user_name: String, + /// The kind of resource this is, in this case dfareporting#userProfile. + pub kind: String, + /// The sub account ID this profile belongs to if applicable. + #[serde(alias="subAccountId")] + pub sub_account_id: String, + /// The account name this profile belongs to. + #[serde(alias="accountName")] + pub account_name: String, + /// The eTag of this response for caching purposes. + pub etag: String, + /// The sub account name this profile belongs to if applicable. + #[serde(alias="subAccountName")] + pub sub_account_name: String, + /// The unique ID of the user profile. + #[serde(alias="profileId")] + pub profile_id: String, + /// The account ID to which this profile belongs. + #[serde(alias="accountId")] + pub account_id: String, +} + +impl Resource for UserProfile {} +impl ResponseResult for UserProfile {} + + +/// Creative Group Assignment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeGroupAssignment { + /// ID of the creative group to be assigned. + #[serde(alias="creativeGroupId")] + pub creative_group_id: String, + /// Creative group number of the creative group assignment. + #[serde(alias="creativeGroupNumber")] + pub creative_group_number: String, +} + +impl Part for CreativeGroupAssignment {} + + +/// The report criteria for a report of type "PATH_TO_CONVERSION". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportPathToConversionCriteria { + /// The list of conversion dimensions the report should include. + #[serde(alias="conversionDimensions")] + pub conversion_dimensions: Vec, + /// The list of names of metrics the report should include. + #[serde(alias="metricNames")] + pub metric_names: Vec, + /// The date range this report should be run for. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// The list of custom floodlight variables the report should include. + #[serde(alias="customFloodlightVariables")] + pub custom_floodlight_variables: Vec, + /// The list of 'dfa:activity' values to filter on. + #[serde(alias="activityFilters")] + pub activity_filters: Vec, + /// The list of custom rich media events to include. + #[serde(alias="customRichMediaEvents")] + pub custom_rich_media_events: Vec, + /// The list of per interaction dimensions the report should include. + #[serde(alias="perInteractionDimensions")] + pub per_interaction_dimensions: Vec, + /// The properties of the report. + #[serde(alias="reportProperties")] + pub report_properties: ReportPathToConversionCriteriaReportProperties, + /// The floodlight ID for which to show data in this report. All advertisers associated with that ID will automatically be added. The dimension of the value needs to be 'dfa:floodlightConfigId'. + #[serde(alias="floodlightConfigId")] + pub floodlight_config_id: DimensionValue, +} + +impl NestedType for ReportPathToConversionCriteria {} +impl Part for ReportPathToConversionCriteria {} + + +/// Creative Field List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creative fields](struct.CreativeFieldListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CreativeFieldsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Creative field collection + #[serde(alias="creativeFields")] + pub creative_fields: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeFieldsListResponse". + pub kind: String, +} + +impl ResponseResult for CreativeFieldsListResponse {} + + +/// The report's email delivery settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportDelivery { + /// The message to be sent with each email. + pub message: String, + /// The type of delivery for the owner to receive, if enabled. + #[serde(alias="emailOwnerDeliveryType")] + pub email_owner_delivery_type: String, + /// The list of recipients to which to email the report. + pub recipients: Vec, + /// Whether the report should be emailed to the report owner. + #[serde(alias="emailOwner")] + pub email_owner: bool, +} + +impl NestedType for ReportDelivery {} +impl Part for ReportDelivery {} + + +/// Geographical Targeting. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GeoTargeting { + /// Regions to be targeted. For each region only dartId is required. The other fields are populated automatically when the ad is inserted or updated. If targeting a region, do not target or exclude the country of the region. + pub regions: Vec, + /// Countries to be targeted or excluded from targeting, depending on the setting of the excludeCountries field. For each country only dartId is required. The other fields are populated automatically when the ad is inserted or updated. If targeting or excluding a country, do not target regions, cities, metros, or postal codes in the same country. + pub countries: Vec, + /// Metros to be targeted. For each metro only dmaId is required. The other fields are populated automatically when the ad is inserted or updated. If targeting a metro, do not target or exclude the country of the metro. + pub metros: Vec, + /// Cities to be targeted. For each city only dartId is required. The other fields are populated automatically when the ad is inserted or updated. If targeting a city, do not target or exclude the country of the city, and do not target the metro or region of the city. + pub cities: Vec, + /// Whether or not to exclude the countries in the countries field from targeting. If false, the countries field refers to countries which will be targeted by the ad. + #[serde(alias="excludeCountries")] + pub exclude_countries: bool, + /// Postal codes to be targeted. For each postal code only id is required. The other fields are populated automatically when the ad is inserted or updated. If targeting a postal code, do not target or exclude the country of the postal code. + #[serde(alias="postalCodes")] + pub postal_codes: Vec, +} + +impl Part for GeoTargeting {} + + +/// Delivery Schedule. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeliverySchedule { + /// Serving priority of an ad, with respect to other ads. The lower the priority number, the greater the priority with which it is served. + pub priority: String, + /// Whether or not hard cutoff is enabled. If true, the ad will not serve after the end date and time. Otherwise the ad will continue to be served until it has reached its delivery goals. + #[serde(alias="hardCutoff")] + pub hard_cutoff: bool, + /// Limit on the number of times an individual user can be served the ad within a specified period of time. + #[serde(alias="frequencyCap")] + pub frequency_cap: FrequencyCap, + /// Impression ratio for this ad. This ratio determines how often each ad is served relative to the others. For example, if ad A has an impression ratio of 1 and ad B has an impression ratio of 3, then DCM will serve ad B three times as often as ad A. Must be between 1 and 10. + #[serde(alias="impressionRatio")] + pub impression_ratio: String, +} + +impl Part for DeliverySchedule {} + + +/// The report's schedule. Can only be set if the report's 'dateRange' is a relative date range and the relative date range is not "TODAY". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportSchedule { + /// Start date of date range for which scheduled reports should be run. + #[serde(alias="startDate")] + pub start_date: String, + /// Enum to define for "MONTHLY" scheduled reports whether reports should be repeated on the same day of the month as "startDate" or the same day of the week of the month. + /// Example: If 'startDate' is Monday, April 2nd 2012 (2012-04-02), "DAY_OF_MONTH" would run subsequent reports on the 2nd of every Month, and "WEEK_OF_MONTH" would run subsequent reports on the first Monday of the month. + #[serde(alias="runsOnDayOfMonth")] + pub runs_on_day_of_month: String, + /// The expiration date when the scheduled report stops running. + #[serde(alias="expirationDate")] + pub expiration_date: String, + /// Whether the schedule is active or not. Must be set to either true or false. + pub active: bool, + /// Defines every how many days, weeks or months the report should be run. Needs to be set when "repeats" is either "DAILY", "WEEKLY" or "MONTHLY". + pub every: i32, + /// The interval for which the report is repeated. Note: + /// - "DAILY" also requires field "every" to be set. + /// - "WEEKLY" also requires fields "every" and "repeatsOnWeekDays" to be set. + /// - "MONTHLY" also requires fields "every" and "runsOnDayOfMonth" to be set. + pub repeats: String, + /// List of week days "WEEKLY" on which scheduled reports should run. + #[serde(alias="repeatsOnWeekDays")] + pub repeats_on_week_days: Vec, +} + +impl NestedType for ReportSchedule {} +impl Part for ReportSchedule {} + + +/// Represents a recipient. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Recipient { + /// The kind of resource this is, in this case dfareporting#recipient. + pub kind: String, + /// The delivery type for the recipient. + #[serde(alias="deliveryType")] + pub delivery_type: String, + /// The email address of the recipient. + pub email: String, +} + +impl Part for Recipient {} + + +/// Represents fields that are compatible to be selected for a report of type "STANDARD". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Vec, + /// The kind of resource this is, in this case dfareporting#reportCompatibleFields. + pub kind: String, + /// Metrics which are compatible to be selected as activity metrics to pivot on in the "activities" section of the report. + #[serde(alias="pivotedActivityMetrics")] + pub pivoted_activity_metrics: Vec, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Vec, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, +} + +impl Part for ReportCompatibleFields {} + + +/// Advertiser Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list advertiser groups](struct.AdvertiserGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdvertiserGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertiserGroupsListResponse". + pub kind: String, + /// Advertiser group collection + #[serde(alias="advertiserGroups")] + pub advertiser_groups: Vec, +} + +impl ResponseResult for AdvertiserGroupsListResponse {} + + +/// Placement Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list placement groups](struct.PlacementGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlacementGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementGroupsListResponse". + pub kind: String, + /// Placement group collection + #[serde(alias="placementGroups")] + pub placement_groups: Vec, +} + +impl ResponseResult for PlacementGroupsListResponse {} + + +/// The properties of the report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportPathToConversionCriteriaReportProperties { + /// DFA checks to see if a click interaction occurred within the specified period of time before a conversion. By default the value is pulled from Floodlight or you can manually enter a custom value. Valid values: 1-90. + #[serde(alias="clicksLookbackWindow")] + pub clicks_lookback_window: i32, + /// Enable pivoting on interaction path. + #[serde(alias="pivotOnInteractionPath")] + pub pivot_on_interaction_path: bool, + /// DFA checks to see if an impression interaction occurred within the specified period of time before a conversion. By default the value is pulled from Floodlight or you can manually enter a custom value. Valid values: 1-90. + #[serde(alias="impressionsLookbackWindow")] + pub impressions_lookback_window: i32, + /// Include conversions that have no associated cookies and no exposures. It’s therefore impossible to know how the user was exposed to your ads during the lookback window prior to a conversion. + #[serde(alias="includeUnattributedIPConversions")] + pub include_unattributed_ip_conversions: bool, + /// Include conversions of users with a DoubleClick cookie but without an exposure. That means the user did not click or see an ad from the advertiser within the Floodlight group, or that the interaction happened outside the lookback window. + #[serde(alias="includeUnattributedCookieConversions")] + pub include_unattributed_cookie_conversions: bool, + /// The maximum amount of time that can take place between interactions (clicks or impressions) by the same user. Valid values: 1-90. + #[serde(alias="maximumInteractionGap")] + pub maximum_interaction_gap: i32, + /// Deprecated: has no effect. + #[serde(alias="includeAttributedIPConversions")] + pub include_attributed_ip_conversions: bool, + /// The maximum number of click interactions to include in the report. Advertisers currently paying for E2C reports get up to 200 (100 clicks, 100 impressions). If another advertiser in your network is paying for E2C, you can have up to 5 total exposures per report. + #[serde(alias="maximumClickInteractions")] + pub maximum_click_interactions: i32, + /// The maximum number of click interactions to include in the report. Advertisers currently paying for E2C reports get up to 200 (100 clicks, 100 impressions). If another advertiser in your network is paying for E2C, you can have up to 5 total exposures per report. + #[serde(alias="maximumImpressionInteractions")] + pub maximum_impression_interactions: i32, +} + +impl NestedType for ReportPathToConversionCriteriaReportProperties {} +impl Part for ReportPathToConversionCriteriaReportProperties {} + + +/// Technology Targeting. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TechnologyTargeting { + /// Browsers that this ad targets. For each browser either set browserVersionId or dartId along with the version numbers. If both are specified, only browserVersionId will be used.The other fields are populated automatically when the ad is inserted or updated. + pub browsers: Vec, + /// Operating systems that this ad targets. To target specific versions, use operatingSystemVersions. For each operating system only dartId is required. The other fields are populated automatically when the ad is inserted or updated. If targeting an operating system, do not set targeting for operating system versions for the same operating system. + #[serde(alias="operatingSystems")] + pub operating_systems: Vec, + /// Mobile carriers that this ad targets. For each mobile carrier only id is required, and the other fields are populated automatically when the ad is inserted or updated. If targeting a mobile carrier, do not set targeting for any zip codes. + #[serde(alias="mobileCarriers")] + pub mobile_carriers: Vec, + /// Connection types that this ad targets. For each connection type only id is required.The other fields are populated automatically when the ad is inserted or updated. + #[serde(alias="connectionTypes")] + pub connection_types: Vec, + /// Platform types that this ad targets. For example, desktop, mobile, or tablet. For each platform type, only id is required, and the other fields are populated automatically when the ad is inserted or updated. + #[serde(alias="platformTypes")] + pub platform_types: Vec, + /// Operating system versions that this ad targets. To target all versions, use operatingSystems. For each operating system version, only id is required. The other fields are populated automatically when the ad is inserted or updated. If targeting an operating system version, do not set targeting for the corresponding operating system in operatingSystems. + #[serde(alias="operatingSystemVersions")] + pub operating_system_versions: Vec, +} + +impl Part for TechnologyTargeting {} + + +/// Creative optimization activity. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OptimizationActivity { + /// Floodlight activity ID of this optimization activity. This is a required field. + #[serde(alias="floodlightActivityId")] + pub floodlight_activity_id: String, + /// Dimension value for the ID of the floodlight activity. This is a read-only, auto-generated field. + #[serde(alias="floodlightActivityIdDimensionValue")] + pub floodlight_activity_id_dimension_value: DimensionValue, + /// Weight associated with this optimization. Must be greater than 1. The weight assigned will be understood in proportion to the weights assigned to the other optimization activities. + pub weight: i32, +} + +impl Part for OptimizationActivity {} + + +/// Remarketing List Targeting Expression. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTargetingExpression { + /// Expression describing which lists are being targeted by the ad. + pub expression: String, +} + +impl Part for ListTargetingExpression {} + + +/// CreativeAssets contains properties of a creative asset file which will be uploaded or has already been uploaded. Refer to the creative sample code for how to upload assets and insert a creative. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert creative assets](struct.CreativeAssetInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeAssetMetadata { + /// Rules validated during code generation that generated a warning. This is a read-only, auto-generated field. + /// + /// Possible values are: + /// - "CLICK_TAG_NON_TOP_LEVEL" + /// - "CLICK_TAG_MISSING" + /// - "CLICK_TAG_MORE_THAN_ONE" + /// - "CLICK_TAG_INVALID" + /// - "ORPHANED_ASSET" + /// - "PRIMARY_HTML_MISSING" + /// - "EXTERNAL_FILE_REFERENCED" + /// - "MRAID_REFERENCED" + /// - "ADMOB_REFERENCED" + /// - "FILE_TYPE_INVALID" + /// - "ZIP_INVALID" + /// - "LINKED_FILE_NOT_FOUND" + /// - "MAX_FLASH_VERSION_11" + /// - "NOT_SSL_COMPLIANT" + /// - "FILE_DETAIL_EMPTY" + /// - "ASSET_INVALID" + /// - "GWD_PROPERTIES_INVALID" + /// - "ENABLER_UNSUPPORTED_METHOD_DCM" + /// - "ASSET_FORMAT_UNSUPPORTED_DCM" + /// - "COMPONENT_UNSUPPORTED_DCM" + /// - "HTML5_FEATURE_UNSUPPORTED' " + #[serde(alias="warnedValidationRules")] + pub warned_validation_rules: Option>, + /// List of feature dependencies for the creative asset that are detected by DCM. Feature dependencies are features that a browser must be able to support in order to render your HTML5 creative correctly. This is a read-only, auto-generated field. + #[serde(alias="detectedFeatures")] + pub detected_features: Option>, + /// List of detected click tags for assets. This is a read-only auto-generated field. + #[serde(alias="clickTags")] + pub click_tags: Option>, + /// ID of the creative asset. This is a required field. + #[serde(alias="assetIdentifier")] + pub asset_identifier: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeAssetMetadata". + pub kind: Option, +} + +impl RequestValue for CreativeAssetMetadata {} +impl ResponseResult for CreativeAssetMetadata {} + + +/// Placement Tag Data +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TagData { + /// Tag string to record a click. + #[serde(alias="clickTag")] + pub click_tag: String, + /// Tag string for serving an ad. + #[serde(alias="impressionTag")] + pub impression_tag: String, + /// Creative associated with this placement tag. + #[serde(alias="creativeId")] + pub creative_id: String, + /// Ad associated with this placement tag. + #[serde(alias="adId")] + pub ad_id: String, + /// TagData tag format of this tag. + pub format: String, +} + +impl Part for TagData {} + + +/// The report criteria for a report of type "FLOODLIGHT". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportFloodlightCriteria { + /// The floodlight ID for which to show data in this report. All advertisers associated with that ID will automatically be added. The dimension of the value needs to be 'dfa:floodlightConfigId'. + #[serde(alias="floodlightConfigId")] + pub floodlight_config_id: DimensionValue, + /// The list of dimensions the report should include. + pub dimensions: Vec, + /// The list of names of metrics the report should include. + #[serde(alias="metricNames")] + pub metric_names: Vec, + /// The date range this report should be run for. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// The list of custom rich media events to include. + #[serde(alias="customRichMediaEvents")] + pub custom_rich_media_events: Vec, + /// The list of filters on which dimensions are filtered. + /// Filters for different dimensions are ANDed, filters for the same dimension are grouped together and ORed. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, + /// The properties of the report. + #[serde(alias="reportProperties")] + pub report_properties: ReportFloodlightCriteriaReportProperties, +} + +impl NestedType for ReportFloodlightCriteria {} +impl Part for ReportFloodlightCriteria {} + + +/// Landing Page List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list landing pages](struct.LandingPageListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct LandingPagesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#landingPagesListResponse". + pub kind: String, + /// Landing page collection + #[serde(alias="landingPages")] + pub landing_pages: Vec, +} + +impl ResponseResult for LandingPagesListResponse {} + + +/// Site List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list sites](struct.SiteListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SitesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#sitesListResponse". + pub kind: String, + /// Site collection + pub sites: Vec, +} + +impl ResponseResult for SitesListResponse {} + + +/// Represents a dimension filter. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DimensionFilter { + /// The name of the dimension to filter. + #[serde(alias="dimensionName")] + pub dimension_name: String, + /// The kind of resource this is, in this case dfareporting#dimensionFilter. + pub kind: String, + /// The value of the dimension to filter. + pub value: String, +} + +impl Part for DimensionFilter {} + + +/// Contains information about a postal code that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list postal codes](struct.PostalCodeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostalCode { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#postalCode". + pub kind: Option, + /// DART ID of the country to which this postal code belongs. + #[serde(alias="countryDartId")] + pub country_dart_id: Option, + /// ID of this postal code. + pub id: Option, + /// Country code of the country to which this postal code belongs. + #[serde(alias="countryCode")] + pub country_code: Option, +} + +impl Resource for PostalCode {} + + +/// Contains properties of a Floodlight activity. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get floodlight activities](struct.FloodlightActivityGetCall.html) (response) +/// * [insert floodlight activities](struct.FloodlightActivityInsertCall.html) (request|response) +/// * [patch floodlight activities](struct.FloodlightActivityPatchCall.html) (request|response) +/// * [update floodlight activities](struct.FloodlightActivityUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FloodlightActivity { + /// Whether this tag should use SSL. + pub secure: Option, + /// Dimension value for the ID of this floodlight activity. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Name of the associated floodlight activity group. This is a read-only field. + #[serde(alias="floodlightActivityGroupName")] + pub floodlight_activity_group_name: Option, + /// Whether the image tag is enabled for this activity. + #[serde(alias="imageTagEnabled")] + pub image_tag_enabled: Option, + /// Advertiser ID of this floodlight activity. If this field is left blank, the value will be copied over either from the activity group's advertiser or the existing activity's advertiser. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Code type used for cache busting in the generated tag. + #[serde(alias="cacheBustingType")] + pub cache_busting_type: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Floodlight activity group ID of this floodlight activity. This is a required field. + #[serde(alias="floodlightActivityGroupId")] + pub floodlight_activity_group_id: Option, + /// List of the user-defined variables used by this conversion tag. These map to the "u[1-20]=" in the tags. Each of these can have a user defined type. + /// Acceptable values are: + /// - "U1" + /// - "U2" + /// - "U3" + /// - "U4" + /// - "U5" + /// - "U6" + /// - "U7" + /// - "U8" + /// - "U9" + /// - "U10" + /// - "U11" + /// - "U12" + /// - "U13" + /// - "U14" + /// - "U15" + /// - "U16" + /// - "U17" + /// - "U18" + /// - "U19" + /// - "U20" + #[serde(alias="userDefinedVariableTypes")] + pub user_defined_variable_types: Option>, + /// Value of the cat= paramter in the floodlight tag, which the ad servers use to identify the activity. This is optional: if empty, a new tag string will be generated for you. This string must be 1 to 8 characters long, with valid characters being [a-z][A-Z][0-9][-][ _ ]. This tag string must also be unique among activities of the same activity group. This field is read-only after insertion. + #[serde(alias="tagString")] + pub tag_string: Option, + /// Tag string of the associated floodlight activity group. This is a read-only field. + #[serde(alias="floodlightActivityGroupTagString")] + pub floodlight_activity_group_tag_string: Option, + /// URL where this tag will be deployed. If specified, must be less than 256 characters long. + #[serde(alias="expectedUrl")] + pub expected_url: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivity". + pub kind: Option, + /// Subaccount ID of this floodlight activity. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this floodlight activity. This is a required field. Must be less than 129 characters long and cannot contain quotes. + pub name: Option, + /// Publisher dynamic floodlight tags. + #[serde(alias="publisherTags")] + pub publisher_tags: Option>, + /// Whether the floodlight activity is SSL-compliant. This is a read-only field, its value detected by the system from the floodlight tags. + #[serde(alias="sslCompliant")] + pub ssl_compliant: Option, + /// General notes or implementation instructions for the tag. + pub notes: Option, + /// Floodlight configuration ID of this floodlight activity. If this field is left blank, the value will be copied over either from the activity group's floodlight configuration or from the existing activity's floodlight configuration. + #[serde(alias="floodlightConfigurationId")] + pub floodlight_configuration_id: Option, + /// ID of this floodlight activity. This is a read-only, auto-generated field. + pub id: Option, + /// Counting method for conversions for this floodlight activity. This is a required field. + #[serde(alias="countingMethod")] + pub counting_method: Option, + /// Dynamic floodlight tags. + #[serde(alias="defaultTags")] + pub default_tags: Option>, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(alias="floodlightConfigurationIdDimensionValue")] + pub floodlight_configuration_id_dimension_value: Option, + /// Tag format type for the floodlight activity. If left blank, the tag format will default to HTML. + #[serde(alias="tagFormat")] + pub tag_format: Option, + /// Whether this activity is archived. + pub hidden: Option, + /// Account ID of this floodlight activity. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Whether this floodlight activity must be SSL-compliant. + #[serde(alias="sslRequired")] + pub ssl_required: Option, + /// Type of the associated floodlight activity group. This is a read-only field. + #[serde(alias="floodlightActivityGroupType")] + pub floodlight_activity_group_type: Option, +} + +impl RequestValue for FloodlightActivity {} +impl ResponseResult for FloodlightActivity {} + + +/// Contains information about a browser that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list browsers](struct.BrowserListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Browser { + /// Major version number (leftmost number) of this browser. For example, for Chrome 5.0.376.86 beta, this field should be set to 5. An asterisk (*) may be used to target any version number, and a question mark (?) may be used to target cases where the version number cannot be identified. For example, Chrome *.* targets any version of Chrome: 1.2, 2.5, 3.5, and so on. Chrome 3.* targets Chrome 3.1, 3.5, but not 4.0. Firefox ?.? targets cases where the ad server knows the browser is Firefox but can't tell which version it is. + #[serde(alias="majorVersion")] + pub major_version: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#browser". + pub kind: Option, + /// ID referring to this grouping of browser and version numbers. This is the ID used for targeting. + #[serde(alias="browserVersionId")] + pub browser_version_id: Option, + /// Name of this browser. + pub name: Option, + /// DART ID of this browser. This is the ID used when generating reports. + #[serde(alias="dartId")] + pub dart_id: Option, + /// Minor version number (number after first dot on left) of this browser. For example, for Chrome 5.0.375.86 beta, this field should be set to 0. An asterisk (*) may be used to target any version number, and a question mark (?) may be used to target cases where the version number cannot be identified. For example, Chrome *.* targets any version of Chrome: 1.2, 2.5, 3.5, and so on. Chrome 3.* targets Chrome 3.1, 3.5, but not 4.0. Firefox ?.? targets cases where the ad server knows the browser is Firefox but can't tell which version it is. + #[serde(alias="minorVersion")] + pub minor_version: Option, +} + +impl Resource for Browser {} + + +/// Account User Profile List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list account user profiles](struct.AccountUserProfileListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountUserProfilesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Account user profile collection + #[serde(alias="accountUserProfiles")] + pub account_user_profiles: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountUserProfilesListResponse". + pub kind: String, +} + +impl ResponseResult for AccountUserProfilesListResponse {} + + +/// Contains properties of a DCM advertiser. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get advertisers](struct.AdvertiserGetCall.html) (response) +/// * [update advertisers](struct.AdvertiserUpdateCall.html) (request|response) +/// * [patch advertisers](struct.AdvertiserPatchCall.html) (request|response) +/// * [list advertisers](struct.AdvertiserListCall.html) (none) +/// * [insert advertisers](struct.AdvertiserInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Advertiser { + /// Status of this advertiser. + pub status: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertiser". + pub kind: Option, + /// Subaccount ID of this advertiser.This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this advertiser. This is a required field and must be less than 256 characters long and unique among advertisers of the same account. + pub name: Option, + /// ID of the click-through event tag to apply by default to the landing pages of this advertiser's campaigns. + #[serde(alias="defaultClickThroughEventTagId")] + pub default_click_through_event_tag_id: Option, + /// Suffix added to click-through URL of ad creative associations under this advertiser. Must be less than 129 characters long. + #[serde(alias="clickThroughUrlSuffix")] + pub click_through_url_suffix: Option, + /// Floodlight configuration ID of this advertiser. The floodlight configuration ID will be created automatically, so on insert this field should be left blank. This field can be set to another advertiser's floodlight configuration ID in order to share that advertiser's floodlight configuration with this advertiser, so long as: + /// - This advertiser's original floodlight configuration is not already associated with floodlight activities or floodlight activity groups. + /// - This advertiser's original floodlight configuration is not already shared with another advertiser. + #[serde(alias="floodlightConfigurationId")] + pub floodlight_configuration_id: Option, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(alias="floodlightConfigurationIdDimensionValue")] + pub floodlight_configuration_id_dimension_value: Option, + /// ID of the advertiser group this advertiser belongs to. You can group advertisers for reporting purposes, allowing you to see aggregated information for all advertisers in each group. + #[serde(alias="advertiserGroupId")] + pub advertiser_group_id: Option, + /// Dimension value for the ID of this advertiser. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Default email address used in sender field for tag emails. + #[serde(alias="defaultEmail")] + pub default_email: Option, + /// ID of this advertiser. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this advertiser.This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for Advertiser {} +impl Resource for Advertiser {} +impl ResponseResult for Advertiser {} + + +/// Platform Type List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list platform types](struct.PlatformTypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlatformTypesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#platformTypesListResponse". + pub kind: String, + /// Platform type collection + #[serde(alias="platformTypes")] + pub platform_types: Vec, +} + +impl ResponseResult for PlatformTypesListResponse {} + + +/// Change Log List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list change logs](struct.ChangeLogListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChangeLogsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#changeLogsListResponse". + pub kind: String, + /// Change log collection + #[serde(alias="changeLogs")] + pub change_logs: Vec, +} + +impl ResponseResult for ChangeLogsListResponse {} + + +/// Placement List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list placements](struct.PlacementListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlacementsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementsListResponse". + pub kind: String, + /// Placement collection + pub placements: Vec, +} + +impl ResponseResult for PlacementsListResponse {} + + +/// Ad List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list ads](struct.AdListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AdsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#adsListResponse". + pub kind: String, + /// Ad collection + pub ads: Vec, +} + +impl ResponseResult for AdsListResponse {} + + +/// The report criteria for a report of type "REACH". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportReachCriteria { + /// Activity group. + pub activities: Activities, + /// The list of dimensions the report should include. + pub dimensions: Vec, + /// The list of names of metrics the report should include. + #[serde(alias="metricNames")] + pub metric_names: Vec, + /// The date range this report should be run for. + #[serde(alias="dateRange")] + pub date_range: DateRange, + /// The list of filters on which dimensions are filtered. + /// Filters for different dimensions are ANDed, filters for the same dimension are grouped together and ORed. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, + /// The list of names of Reach By Frequency metrics the report should include. + #[serde(alias="reachByFrequencyMetricNames")] + pub reach_by_frequency_metric_names: Vec, + /// Custom Rich Media Events group. + #[serde(alias="customRichMediaEvents")] + pub custom_rich_media_events: CustomRichMediaEvents, + /// Whether to enable all reach dimension combinations in the report. Defaults to false. If enabled, the date range of the report should be within the last three months. + #[serde(alias="enableAllDimensionCombinations")] + pub enable_all_dimension_combinations: bool, +} + +impl NestedType for ReportReachCriteria {} +impl Part for ReportReachCriteria {} + + +/// The URLs where the completed report file can be downloaded. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FileUrls { + /// The URL for downloading the report data through a browser. + #[serde(alias="browserUrl")] + pub browser_url: String, + /// The URL for downloading the report data through the API. + #[serde(alias="apiUrl")] + pub api_url: String, +} + +impl NestedType for FileUrls {} +impl Part for FileUrls {} + + +/// User Defined Variable configuration. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserDefinedVariableConfiguration { + /// Data type for the variable. This is a required field. + #[serde(alias="dataType")] + pub data_type: String, + /// User-friendly name for the variable which will appear in reports. This is a required field, must be less than 64 characters long, and cannot contain the following characters: ""<>". + #[serde(alias="reportName")] + pub report_name: String, + /// Variable name in the tag. This is a required field. + #[serde(alias="variableType")] + pub variable_type: String, +} + +impl Part for UserDefinedVariableConfiguration {} + + +/// Publisher Dynamic Tag +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FloodlightActivityPublisherDynamicTag { + /// Whether this tag is applicable only for view-throughs. + #[serde(alias="viewThrough")] + pub view_through: bool, + /// Site ID of this dynamic tag. + #[serde(alias="siteId")] + pub site_id: String, + /// Whether this tag is applicable only for click-throughs. + #[serde(alias="clickThrough")] + pub click_through: bool, + /// Directory site ID of this dynamic tag. This is a write-only field that can be used as an alternative to the siteId field. When this resource is retrieved, only the siteId field will be populated. + #[serde(alias="directorySiteId")] + pub directory_site_id: String, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(alias="siteIdDimensionValue")] + pub site_id_dimension_value: DimensionValue, + /// Dynamic floodlight tag. + #[serde(alias="dynamicTag")] + pub dynamic_tag: FloodlightActivityDynamicTag, +} + +impl Part for FloodlightActivityPublisherDynamicTag {} + + +/// Contains information about where a user's browser is taken after the user clicks an ad. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update landing pages](struct.LandingPageUpdateCall.html) (request|response) +/// * [list landing pages](struct.LandingPageListCall.html) (none) +/// * [patch landing pages](struct.LandingPagePatchCall.html) (request|response) +/// * [insert landing pages](struct.LandingPageInsertCall.html) (request|response) +/// * [delete landing pages](struct.LandingPageDeleteCall.html) (none) +/// * [get landing pages](struct.LandingPageGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LandingPage { + /// Whether or not this landing page will be assigned to any ads or creatives that do not have a landing page assigned explicitly. Only one default landing page is allowed per campaign. + pub default: Option, + /// URL of this landing page. This is a required field. + pub url: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#landingPage". + pub kind: Option, + /// ID of this landing page. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this landing page. This is a required field. Must be less than 256 characters long, and must be unique among landing pages of the same campaign. + pub name: Option, +} + +impl RequestValue for LandingPage {} +impl Resource for LandingPage {} +impl ResponseResult for LandingPage {} + + +/// Represents the dimensions of ads, placements, creatives, or creative assets. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert sizes](struct.SizeInsertCall.html) (request|response) +/// * [get sizes](struct.SizeGetCall.html) (response) +/// * [list sizes](struct.SizeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Size { + /// Width of this size. + pub width: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#size". + pub kind: Option, + /// Height of this size. + pub height: Option, + /// ID of this size. This is a read-only, auto-generated field. + pub id: Option, + /// IAB standard size. This is a read-only, auto-generated field. + pub iab: Option, +} + +impl RequestValue for Size {} +impl Resource for Size {} +impl ResponseResult for Size {} + + +/// Contains information about a city that can be targeted by ads. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct City { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#city". + pub kind: String, + /// DART ID of the country to which this city belongs. + #[serde(alias="countryDartId")] + pub country_dart_id: String, + /// Name of this city. + pub name: String, + /// Country code of the country to which this city belongs. + #[serde(alias="countryCode")] + pub country_code: String, + /// Metro region code of the metro region (DMA) to which this city belongs. + #[serde(alias="metroCode")] + pub metro_code: String, + /// Region code of the region to which this city belongs. + #[serde(alias="regionCode")] + pub region_code: String, + /// ID of the metro region (DMA) to which this city belongs. + #[serde(alias="metroDmaId")] + pub metro_dma_id: String, + /// DART ID of this city. This is the ID used for targeting and generating reports. + #[serde(alias="dartId")] + pub dart_id: String, + /// DART ID of the region to which this city belongs. + #[serde(alias="regionDartId")] + pub region_dart_id: String, +} + +impl Part for City {} + + +/// Click Through URL Suffix settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ClickThroughUrlSuffixProperties { + /// Click-through URL suffix to apply to all ads in this entity's scope. Must be less than 128 characters long. + #[serde(alias="clickThroughUrlSuffix")] + pub click_through_url_suffix: String, + /// Whether this entity should override the inherited click-through URL suffix with its own defined value. + #[serde(alias="overrideInheritedSuffix")] + pub override_inherited_suffix: bool, +} + +impl Part for ClickThroughUrlSuffixProperties {} + + +/// Contains properties of a package or roadblock. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update placement groups](struct.PlacementGroupUpdateCall.html) (request|response) +/// * [patch placement groups](struct.PlacementGroupPatchCall.html) (request|response) +/// * [get placement groups](struct.PlacementGroupGetCall.html) (response) +/// * [insert placement groups](struct.PlacementGroupInsertCall.html) (request|response) +/// * [list placement groups](struct.PlacementGroupListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PlacementGroup { + /// Comments for this placement group. + pub comment: Option, + /// ID of the primary placement, used to calculate the media cost of a roadblock (placement group). Modifying this field will automatically modify the primary field on all affected roadblock child placements. + #[serde(alias="primaryPlacementId")] + pub primary_placement_id: Option, + /// Campaign ID of this placement group. This field is required on insertion. + #[serde(alias="campaignId")] + pub campaign_id: Option, + /// Dimension value for the ID of the primary placement. This is a read-only, auto-generated field. + #[serde(alias="primaryPlacementIdDimensionValue")] + pub primary_placement_id_dimension_value: Option, + /// Dimension value for the ID of the directory site. This is a read-only, auto-generated field. + #[serde(alias="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Advertiser ID of this placement group. This is a required field on insertion. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Directory site ID associated with this placement group. On insert, you must set either this field or the site_id field to specify the site associated with this placement group. This is a required field that is read-only after insertion. + #[serde(alias="directorySiteId")] + pub directory_site_id: Option, + /// Information about the creation of this placement group. This is a read-only field. + #[serde(alias="createInfo")] + pub create_info: Option, + /// Site ID associated with this placement group. On insert, you must set either this field or the directorySiteId field to specify the site associated with this placement group. This is a required field that is read-only after insertion. + #[serde(alias="siteId")] + pub site_id: Option, + /// Pricing schedule of this placement group. This field is required on insertion. + #[serde(alias="pricingSchedule")] + pub pricing_schedule: Option, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(alias="siteIdDimensionValue")] + pub site_id_dimension_value: Option, + /// Type of this placement group. A package is a simple group of placements that acts as a single pricing point for a group of tags. A roadblock is a group of placements that not only acts as a single pricing point, but also assumes that all the tags in it will be served at the same time. A roadblock requires one of its assigned placements to be marked as primary for reporting. This field is required on insertion. + #[serde(alias="placementGroupType")] + pub placement_group_type: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Whether this placement group is archived. + pub archived: Option, + /// ID of this placement group. This is a read-only, auto-generated field. + pub id: Option, + /// ID of the placement strategy assigned to this placement group. + #[serde(alias="placementStrategyId")] + pub placement_strategy_id: Option, + /// Account ID of this placement group. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Settings for a programmatic placement. + #[serde(alias="programmaticSetting")] + pub programmatic_setting: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(alias="campaignIdDimensionValue")] + pub campaign_id_dimension_value: Option, + /// Subaccount ID of this placement group. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this placement group. This is a required field and must be less than 256 characters long. + pub name: Option, + /// IDs of placements which are assigned to this placement group. This is a read-only, auto-generated field. + #[serde(alias="childPlacementIds")] + pub child_placement_ids: Option>, + /// Information about the most recent modification of this placement group. This is a read-only field. + #[serde(alias="lastModifiedInfo")] + pub last_modified_info: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementGroup". + pub kind: Option, + /// ID of the content category assigned to this placement group. + #[serde(alias="contentCategoryId")] + pub content_category_id: Option, + /// External ID for this placement. + #[serde(alias="externalId")] + pub external_id: Option, + /// Dimension value for the ID of this placement group. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, +} + +impl RequestValue for PlacementGroup {} +impl Resource for PlacementGroup {} +impl ResponseResult for PlacementGroup {} + + +/// Third-party Tracking URL. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ThirdPartyTrackingUrl { + /// URL for the specified third-party URL type. + pub url: String, + /// Third-party URL type for in-stream video creatives. + #[serde(alias="thirdPartyUrlType")] + pub third_party_url_type: String, +} + +impl Part for ThirdPartyTrackingUrl {} + + +/// Contains properties of a user role permission. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get user role permissions](struct.UserRolePermissionGetCall.html) (response) +/// * [list user role permissions](struct.UserRolePermissionListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserRolePermission { + /// ID of the permission group that this user role permission belongs to. + #[serde(alias="permissionGroupId")] + pub permission_group_id: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermission". + pub kind: String, + /// Levels of availability for a user role permission. + pub availability: String, + /// ID of this user role permission. + pub id: String, + /// Name of this user role permission. + pub name: String, +} + +impl Resource for UserRolePermission {} +impl ResponseResult for UserRolePermission {} + + +/// Metro List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list metros](struct.MetroListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct MetrosListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#metrosListResponse". + pub kind: String, + /// Metro collection + pub metros: Vec, +} + +impl ResponseResult for MetrosListResponse {} + + +/// Pricing Schedule +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PricingSchedule { + /// Placement start date. This date cannot be earlier than the campaign start date. The hours, minutes, and seconds of the start date should not be set, as doing so will result in an error. This field is required on insertion. + #[serde(alias="startDate")] + pub start_date: String, + /// Placement end date. This date must be later than or be the same day as the placement start date, but not later than the campaign end date. If, for example, you set 6/25/2015 as both the start and end dates, the effective placement date is just that day only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so will result in an error. This field is required on insertion. + #[serde(alias="endDate")] + pub end_date: String, + /// Whether this placement is flighted. If true, pricing periods will be computed automatically. + pub flighted: bool, + /// Whether cap costs are ignored by ad serving. + #[serde(alias="disregardOverdelivery")] + pub disregard_overdelivery: bool, + /// Placement cap cost option. + #[serde(alias="capCostOption")] + pub cap_cost_option: String, + /// Pricing periods for this placement. + #[serde(alias="pricingPeriods")] + pub pricing_periods: Vec, + /// Placement pricing type. This field is required on insertion. + #[serde(alias="pricingType")] + pub pricing_type: String, + /// Testing start date of this placement. The hours, minutes, and seconds of the start date should not be set, as doing so will result in an error. + #[serde(alias="testingStartDate")] + pub testing_start_date: String, + /// Floodlight activity ID associated with this placement. This field should be set when placement pricing type is set to PRICING_TYPE_CPA. + #[serde(alias="floodlightActivityId")] + pub floodlight_activity_id: String, +} + +impl Part for PricingSchedule {} + + +/// Account List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list accounts](struct.AccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountsListResponse". + pub kind: String, + /// Account collection + pub accounts: Vec, +} + +impl ResponseResult for AccountsListResponse {} + + +/// Contains information about an operating system that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list operating systems](struct.OperatingSystemListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OperatingSystem { + /// Whether this operating system is for mobile. + pub mobile: Option, + /// DART ID of this operating system. This is the ID used for targeting. + #[serde(alias="dartId")] + pub dart_id: Option, + /// Whether this operating system is for desktop. + pub desktop: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystem". + pub kind: Option, + /// Name of this operating system. + pub name: Option, +} + +impl Resource for OperatingSystem {} + + +/// Represents an activity group. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Activities { + /// The kind of resource this is, in this case dfareporting#activities. + pub kind: String, + /// List of activity filters. The dimension values need to be all either of type "dfa:activity" or "dfa:activityGroup". + pub filters: Vec, + /// List of names of floodlight activity metrics. + #[serde(alias="metricNames")] + pub metric_names: Vec, +} + +impl Part for Activities {} + + +/// Represents a sorted dimension. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SortedDimension { + /// The kind of resource this is, in this case dfareporting#sortedDimension. + pub kind: String, + /// The name of the dimension. + pub name: String, + /// An optional sort order for the dimension column. + #[serde(alias="sortOrder")] + pub sort_order: String, +} + +impl Part for SortedDimension {} + + +/// Placement Strategy List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list placement strategies](struct.PlacementStrategyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PlacementStrategiesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementStrategiesListResponse". + pub kind: String, + /// Placement strategy collection + #[serde(alias="placementStrategies")] + pub placement_strategies: Vec, +} + +impl ResponseResult for PlacementStrategiesListResponse {} + + +/// Represents the list of reports. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list reports](struct.ReportListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportList { + /// Continuation token used to page through reports. To retrieve the next page of results, set the next request's "pageToken" to the value of this field. The page token is only valid for a limited amount of time and should not be persisted. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The reports returned in this response. + pub items: Vec, + /// The kind of list this is, in this case dfareporting#reportList. + pub kind: String, + /// The eTag of this response for caching purposes. + pub etag: String, +} + +impl ResponseResult for ReportList {} + + +/// Groups advertisers together so that reports can be generated for the entire group at once. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete advertiser groups](struct.AdvertiserGroupDeleteCall.html) (none) +/// * [get advertiser groups](struct.AdvertiserGroupGetCall.html) (response) +/// * [update advertiser groups](struct.AdvertiserGroupUpdateCall.html) (request|response) +/// * [list advertiser groups](struct.AdvertiserGroupListCall.html) (none) +/// * [patch advertiser groups](struct.AdvertiserGroupPatchCall.html) (request|response) +/// * [insert advertiser groups](struct.AdvertiserGroupInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdvertiserGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertiserGroup". + pub kind: Option, + /// Account ID of this advertiser group. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// ID of this advertiser group. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this advertiser group. This is a required field and must be less than 256 characters long and unique among advertiser groups of the same account. + pub name: Option, +} + +impl RequestValue for AdvertiserGroup {} +impl Resource for AdvertiserGroup {} +impl ResponseResult for AdvertiserGroup {} + + +/// FsCommand. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FsCommand { + /// Height of the window. + #[serde(alias="windowHeight")] + pub window_height: i32, + /// Distance from the top of the browser. Applicable when positionOption is DISTANCE_FROM_TOP_LEFT_CORNER. + pub top: i32, + /// Width of the window. + #[serde(alias="windowWidth")] + pub window_width: i32, + /// Position in the browser where the window will open. + #[serde(alias="positionOption")] + pub position_option: String, + /// Distance from the left of the browser.Applicable when positionOption is DISTANCE_FROM_TOP_LEFT_CORNER. + pub left: i32, +} + +impl Part for FsCommand {} + + +/// Creative optimization settings. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeOptimizationConfiguration { + /// List of optimization activities associated with this configuration. + #[serde(alias="optimizationActivitys")] + pub optimization_activitys: Vec, + /// ID of this creative optimization config. This field is auto-generated when the campaign is inserted or updated. It can be null for existing campaigns. + pub id: String, + /// Name of this creative optimization config. This is a required field and must be less than 129 characters long. + pub name: String, + /// Optimization model for this configuration. + #[serde(alias="optimizationModel")] + pub optimization_model: String, +} + +impl Part for CreativeOptimizationConfiguration {} + + +/// Creative Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creative groups](struct.CreativeGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CreativeGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Creative group collection + #[serde(alias="creativeGroups")] + pub creative_groups: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeGroupsListResponse". + pub kind: String, +} + +impl ResponseResult for CreativeGroupsListResponse {} + + +/// Offset Position. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OffsetPosition { + /// Offset distance from top side of an asset or a window. + pub top: i32, + /// Offset distance from left side of an asset or a window. + pub left: i32, +} + +impl Part for OffsetPosition {} + + +/// Target Window. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetWindow { + /// User-entered value. + #[serde(alias="customHtml")] + pub custom_html: String, + /// Type of browser window for which the backup image of the flash creative can be displayed. + #[serde(alias="targetWindowOption")] + pub target_window_option: String, +} + +impl Part for TargetWindow {} + + +/// Programmatic Setting +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProgrammaticSetting { + /// Trafficker emails assigned to the placement. + #[serde(alias="traffickerEmails")] + pub trafficker_emails: Vec, + /// Whether programmatic is enabled. + pub programmatic: bool, + /// Media cost for the programmatic placement. + #[serde(alias="mediaCostNanos")] + pub media_cost_nanos: String, + /// Adx deal IDs assigned to the placement. + #[serde(alias="adxDealIds")] + pub adx_deal_ids: Vec, + /// Insertion order ID. + #[serde(alias="insertionOrderId")] + pub insertion_order_id: String, + /// Whether insertion order ID has been placed in DFP. This is a read-only field. + #[serde(alias="insertionOrderIdStatus")] + pub insertion_order_id_status: bool, +} + +impl Part for ProgrammaticSetting {} + + +/// Site Contact +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SiteContact { + /// Last name of this site contact. + #[serde(alias="lastName")] + pub last_name: String, + /// Site contact type. + #[serde(alias="contactType")] + pub contact_type: String, + /// Email address of this site contact. This is a required field. + pub email: String, + /// First name of this site contact. + #[serde(alias="firstName")] + pub first_name: String, + /// ID of this site contact. This is a read-only, auto-generated field. + pub id: String, +} + +impl Part for SiteContact {} + + +/// Creative Rotation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeRotation { + /// Creative assignments in this creative rotation. + #[serde(alias="creativeAssignments")] + pub creative_assignments: Vec, + /// Strategy for calculating weights. Used with CREATIVE_ROTATION_TYPE_RANDOM. + #[serde(alias="weightCalculationStrategy")] + pub weight_calculation_strategy: String, + /// Creative optimization configuration that is used by this ad. It should refer to one of the existing optimization configurations in the ad's campaign. If it is unset or set to 0, then the campaign's default optimization configuration will be used for this ad. + #[serde(alias="creativeOptimizationConfigurationId")] + pub creative_optimization_configuration_id: String, + /// Type of creative rotation. Can be used to specify whether to use sequential or random rotation. + #[serde(alias="type")] + pub type_: String, +} + +impl Part for CreativeRotation {} + + +/// Contains information about a metro region that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list metros](struct.MetroListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Metro { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#metro". + pub kind: Option, + /// DART ID of the country to which this metro region belongs. + #[serde(alias="countryDartId")] + pub country_dart_id: Option, + /// Name of this metro region. + pub name: Option, + /// Country code of the country to which this metro region belongs. + #[serde(alias="countryCode")] + pub country_code: Option, + /// Metro code of this metro region. This is equivalent to dma_id. + #[serde(alias="metroCode")] + pub metro_code: Option, + /// DART ID of this metro region. + #[serde(alias="dartId")] + pub dart_id: Option, + /// DMA ID of this metro region. This is the ID used for targeting and generating reports, and is equivalent to metro_code. + #[serde(alias="dmaId")] + pub dma_id: Option, +} + +impl Resource for Metro {} + + +/// Contains information about a country that can be targeted by ads. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get countries](struct.CountryGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Country { + /// DART ID of this country. This is the ID used for targeting and generating reports. + #[serde(alias="dartId")] + pub dart_id: String, + /// Whether ad serving supports secure servers in this country. + #[serde(alias="sslEnabled")] + pub ssl_enabled: bool, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#country". + pub kind: String, + /// Country code. + #[serde(alias="countryCode")] + pub country_code: String, + /// Name of this country. + pub name: String, +} + +impl ResponseResult for Country {} + + +/// Postal Code List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list postal codes](struct.PostalCodeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PostalCodesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#postalCodesListResponse". + pub kind: String, + /// Postal code collection + #[serde(alias="postalCodes")] + pub postal_codes: Vec, +} + +impl ResponseResult for PostalCodesListResponse {} + + +/// Tag Settings +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TagSetting { + /// Whether static landing page URLs should be included in the tags. This setting applies only to placements. + #[serde(alias="includeClickThroughUrls")] + pub include_click_through_urls: bool, + /// Whether click-tracking string should be included in the tags. + #[serde(alias="includeClickTracking")] + pub include_click_tracking: bool, + /// Additional key-values to be included in tags. Each key-value pair must be of the form key=value, and pairs must be separated by a semicolon (;). Keys and values must not contain commas. For example, id=2;color=red is a valid value for this field. + #[serde(alias="additionalKeyValues")] + pub additional_key_values: String, + /// Option specifying how keywords are embedded in ad tags. This setting can be used to specify whether keyword placeholders are inserted in placement tags for this site. Publishers can then add keywords to those placeholders. + #[serde(alias="keywordOption")] + pub keyword_option: String, +} + +impl Part for TagSetting {} + + +/// Contains properties of an event tag. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete event tags](struct.EventTagDeleteCall.html) (none) +/// * [patch event tags](struct.EventTagPatchCall.html) (request|response) +/// * [list event tags](struct.EventTagListCall.html) (none) +/// * [update event tags](struct.EventTagUpdateCall.html) (request|response) +/// * [insert event tags](struct.EventTagInsertCall.html) (request|response) +/// * [get event tags](struct.EventTagGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EventTag { + /// Status of this event tag. Must be ENABLED for this event tag to fire. This is a required field. + pub status: Option, + /// Filter list of site IDs associated with this event tag. The siteFilterType determines whether this is a whitelist or blacklist filter. + #[serde(alias="siteIds")] + pub site_ids: Option>, + /// Campaign ID of this event tag. This field or the advertiserId field is required on insertion. + #[serde(alias="campaignId")] + pub campaign_id: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(alias="campaignIdDimensionValue")] + pub campaign_id_dimension_value: Option, + /// Whether this event tag should be automatically enabled for all of the advertiser's campaigns and ads. + #[serde(alias="enabledByDefault")] + pub enabled_by_default: Option, + /// Advertiser ID of this event tag. This field or the campaignId field is required on insertion. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Site filter type for this event tag. If no type is specified then the event tag will be applied to all sites. + #[serde(alias="siteFilterType")] + pub site_filter_type: Option, + /// Event tag type. Can be used to specify whether to use a third-party pixel, a third-party JavaScript URL, or a third-party click-through URL for either impression or click tracking. This is a required field. + #[serde(alias="type")] + pub type_: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of this event tag. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this event tag. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#eventTag". + pub kind: Option, + /// Subaccount ID of this event tag. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this event tag. This is a required field and must be less than 256 characters long. + pub name: Option, + /// Payload URL for this event tag. The URL on a click-through event tag should have a landing page URL appended to the end of it. This field is required on insertion. + pub url: Option, + /// Whether this tag is SSL-compliant or not. + #[serde(alias="sslCompliant")] + pub ssl_compliant: Option, + /// Number of times the landing page URL should be URL-escaped before being appended to the click-through event tag URL. Only applies to click-through event tags as specified by the event tag type. + #[serde(alias="urlEscapeLevels")] + pub url_escape_levels: Option, +} + +impl RequestValue for EventTag {} +impl Resource for EventTag {} +impl ResponseResult for EventTag {} + + +/// Creative Field Value List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list creative field values](struct.CreativeFieldValueListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CreativeFieldValuesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeFieldValuesListResponse". + pub kind: String, + /// Creative field value collection + #[serde(alias="creativeFieldValues")] + pub creative_field_values: Vec, +} + +impl ResponseResult for CreativeFieldValuesListResponse {} + + +/// Contains properties of a Site Directory contact. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get directory site contacts](struct.DirectorySiteContactGetCall.html) (response) +/// * [list directory site contacts](struct.DirectorySiteContactListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DirectorySiteContact { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySiteContact". + pub kind: String, + /// Directory site contact role. + pub role: String, + /// First name of this directory site contact. + #[serde(alias="firstName")] + pub first_name: String, + /// Last name of this directory site contact. + #[serde(alias="lastName")] + pub last_name: String, + /// Directory site contact type. + #[serde(alias="type")] + pub type_: String, + /// Email address of this directory site contact. + pub email: String, + /// ID of this directory site contact. This is a read-only, auto-generated field. + pub id: String, +} + +impl Resource for DirectorySiteContact {} +impl ResponseResult for DirectorySiteContact {} + + +/// Represents a DimensionValue resource. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [query dimension values](struct.DimensionValueQueryCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DimensionValue { + /// The name of the dimension. + #[serde(alias="dimensionName")] + pub dimension_name: Option, + /// The kind of resource this is, in this case dfareporting#dimensionValue. + pub kind: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, + /// Determines how the 'value' field is matched when filtering. If not specified, defaults to EXACT. If set to WILDCARD_EXPRESSION, '*' is allowed as a placeholder for variable length character sequences, and it can be escaped with a backslash. Note, only paid search dimensions ('dfa:paidSearch*') allow a matchType other than EXACT. + #[serde(alias="matchType")] + pub match_type: Option, + /// The ID associated with the value if available. + pub id: Option, + /// The value of the dimension. + pub value: Option, +} + +impl Resource for DimensionValue {} + + +/// Content Category List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list content categories](struct.ContentCategoryListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ContentCategoriesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#contentCategoriesListResponse". + pub kind: String, + /// Content category collection + #[serde(alias="contentCategories")] + pub content_categories: Vec, +} + +impl ResponseResult for ContentCategoriesListResponse {} + + +/// Floodlight Configuration List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list floodlight configurations](struct.FloodlightConfigurationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FloodlightConfigurationsListResponse { + /// Floodlight configuration collection + #[serde(alias="floodlightConfigurations")] + pub floodlight_configurations: Vec, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightConfigurationsListResponse". + pub kind: String, +} + +impl ResponseResult for FloodlightConfigurationsListResponse {} + + +/// Popup Window Properties. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PopupWindowProperties { + /// Whether to display the browser status bar. + #[serde(alias="showStatusBar")] + pub show_status_bar: bool, + /// Whether to display the browser scroll bar. + #[serde(alias="showScrollBar")] + pub show_scroll_bar: bool, + /// Whether to display the browser address bar. + #[serde(alias="showAddressBar")] + pub show_address_bar: bool, + /// Whether to display the browser menu bar. + #[serde(alias="showMenuBar")] + pub show_menu_bar: bool, + /// Title of popup window. + pub title: String, + /// Upper-left corner coordinates of the popup window. Applicable if positionType is COORDINATES. + pub offset: OffsetPosition, + /// Popup window position either centered or at specific coordinate. + #[serde(alias="positionType")] + pub position_type: String, + /// Whether to display the browser tool bar. + #[serde(alias="showToolBar")] + pub show_tool_bar: bool, + /// Popup dimension for a creative. This is a read-only field. Applicable to the following creative types: all RICH_MEDIA and all VPAID + pub dimension: Size, +} + +impl Part for PopupWindowProperties {} + + +/// AccountPermissions contains information about a particular account permission. Some features of DCM require an account permission to be present in the account. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list account permissions](struct.AccountPermissionListCall.html) (none) +/// * [get account permissions](struct.AccountPermissionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountPermission { + /// Permission group of this account permission. + #[serde(alias="permissionGroupId")] + pub permission_group_id: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermission". + pub kind: String, + /// Name of this account permission. + pub name: String, + /// Administrative level required to enable this account permission. + pub level: String, + /// Account profiles associated with this account permission. + /// + /// Possible values are: + /// - "ACCOUNT_PROFILE_BASIC" + /// - "ACCOUNT_PROFILE_STANDARD" + #[serde(alias="accountProfiles")] + pub account_profiles: Vec, + /// ID of this account permission. + pub id: String, +} + +impl Resource for AccountPermission {} +impl ResponseResult for AccountPermission {} + + +/// Contains properties of a DCM ad. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch ads](struct.AdPatchCall.html) (request|response) +/// * [list ads](struct.AdListCall.html) (none) +/// * [insert ads](struct.AdInsertCall.html) (request|response) +/// * [get ads](struct.AdGetCall.html) (response) +/// * [update ads](struct.AdUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Ad { + /// Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding ad properties) the URL in the creative. + #[serde(alias="clickThroughUrlSuffixProperties")] + pub click_through_url_suffix_properties: Option, + /// Campaign ID of this ad. This is a required field on insertion. + #[serde(alias="campaignId")] + pub campaign_id: Option, + /// Advertiser ID of this ad. This is a required field on insertion. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Geographical targeting information for this ad.Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(alias="geoTargeting")] + pub geo_targeting: Option, + /// Comments for this ad. + pub comments: Option, + /// Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required on insertion when type is AD_SERVING_STANDARD_AD. + #[serde(alias="deliverySchedule")] + pub delivery_schedule: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Event tag overrides for this ad. + #[serde(alias="eventTagOverrides")] + pub event_tag_overrides: Option>, + /// ID of this ad. This is a read-only, auto-generated field. + pub id: Option, + /// Applicable when type is AD_SERVING_STANDARD_AD. Remarketing list targeting expression for this ad. + pub remarketing_list_expression: Option, + /// Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. + pub size: Option, + /// Whether this ad is archived. + pub archived: Option, + /// Technology platform targeting information for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(alias="technologyTargeting")] + pub technology_targeting: Option, + /// Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD, AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field should have exactly one creativeAssignment. + #[serde(alias="creativeRotation")] + pub creative_rotation: Option, + /// Click-through URL for this ad. This is a required field on insertion. Applicable when type is AD_SERVING_CLICK_TRACKER. + #[serde(alias="clickThroughUrl")] + pub click_through_url: Option, + /// Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only one assignment per creative group number is allowed for a maximum of two assignments. + #[serde(alias="creativeGroupAssignments")] + pub creative_group_assignments: Option>, + /// Dimension value for the ID of this ad. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Account ID of this ad. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Type of ad. This is a required field on insertion. Note that default ads (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource). + #[serde(alias="type")] + pub type_: Option, + /// Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is inserted or updated. + #[serde(alias="sslRequired")] + pub ssl_required: Option, + /// Audience segment ID that is being targeted for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(alias="audienceSegmentId")] + pub audience_segment_id: Option, + /// Key-value targeting information for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(alias="keyValueTargetingExpression")] + pub key_value_targeting_expression: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(alias="campaignIdDimensionValue")] + pub campaign_id_dimension_value: Option, + /// Default click-through event tag properties for this ad. + #[serde(alias="defaultClickThroughEventTagProperties")] + pub default_click_through_event_tag_properties: Option, + /// Information about the creation of this ad.This is a read-only field. + #[serde(alias="createInfo")] + pub create_info: Option, + /// Date and time that this ad should start serving. If creating an ad, this field must be a time in the future. This is a required field on insertion. + #[serde(alias="startTime")] + pub start_time: Option, + /// Whether this ad is active. + pub active: Option, + /// Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. WEB and WEB_INTERSTITIAL refer to rendering either on desktop or on mobile devices for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are for rendering in mobile apps. IN_STREAM_VIDEO refers to rendering an in-stream video ads developed with the VAST standard. + pub compatibility: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad". + pub kind: Option, + /// Subaccount ID of this ad. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this ad. This is a required field and must be less than 256 characters long. + pub name: Option, + /// Time and day targeting information for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(alias="dayPartTargeting")] + pub day_part_targeting: Option, + /// Information about the most recent modification of this ad. This is a read-only field. + #[serde(alias="lastModifiedInfo")] + pub last_modified_info: Option, + /// Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad is inserted or updated. + #[serde(alias="sslCompliant")] + pub ssl_compliant: Option, + /// Date and time that this ad should stop serving. Must be later than the start time. This is a required field on insertion. + #[serde(alias="endTime")] + pub end_time: Option, + /// Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER. This is a required field on insert, and is read-only after insert. + #[serde(alias="dynamicClickTracker")] + pub dynamic_click_tracker: Option, + /// Placement assignments for this ad. + #[serde(alias="placementAssignments")] + pub placement_assignments: Option>, +} + +impl RequestValue for Ad {} +impl Resource for Ad {} +impl ResponseResult for Ad {} + + +/// Pricing Period +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PricingSchedulePricingPeriod { + /// Units of this pricing period. + pub units: String, + /// Pricing period start date. This date cannot be earlier than the placement start date. The hours, minutes, and seconds of the start date should not be set, as doing so will result in an error. + #[serde(alias="startDate")] + pub start_date: String, + /// Rate or cost of this pricing period. + #[serde(alias="rateOrCostNanos")] + pub rate_or_cost_nanos: String, + /// Pricing period end date. This date must be later than or be the same day as the pricing period start date, but not later than the placement end date. The period end date can be the same date as the period start date. If, for example, you set 6/25/2015 as both the start and end dates, the effective pricing period date is just that day only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so will result in an error. + #[serde(alias="endDate")] + pub end_date: String, + /// Comments for this pricing period. + #[serde(alias="pricingComment")] + pub pricing_comment: String, +} + +impl Part for PricingSchedulePricingPeriod {} + + +/// Placement Assignment. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PlacementAssignment { + /// Whether this placement assignment is active. When true, the placement will be included in the ad's rotation. + pub active: bool, + /// Dimension value for the ID of the placement. This is a read-only, auto-generated field. + #[serde(alias="placementIdDimensionValue")] + pub placement_id_dimension_value: DimensionValue, + /// ID of the placement to be assigned. This is a required field. + #[serde(alias="placementId")] + pub placement_id: String, + /// Whether the placement to be assigned requires SSL. This is a read-only field that is auto-generated when the ad is inserted or updated. + #[serde(alias="sslRequired")] + pub ssl_required: bool, +} + +impl Part for PlacementAssignment {} + + +/// Represents fields that are compatible to be selected for a report of type "REACH". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReachReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Vec, + /// The kind of resource this is, in this case dfareporting#reachReportCompatibleFields. + pub kind: String, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Vec, + /// Metrics which are compatible to be selected in the "reachByFrequencyMetricNames" section of the report. + #[serde(alias="reachByFrequencyMetrics")] + pub reach_by_frequency_metrics: Vec, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(alias="dimensionFilters")] + pub dimension_filters: Vec, + /// Metrics which are compatible to be selected as activity metrics to pivot on in the "activities" section of the report. + #[serde(alias="pivotedActivityMetrics")] + pub pivoted_activity_metrics: Vec, +} + +impl Part for ReachReportCompatibleFields {} + + +/// Contains properties of a site. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update sites](struct.SiteUpdateCall.html) (request|response) +/// * [list sites](struct.SiteListCall.html) (none) +/// * [insert sites](struct.SiteInsertCall.html) (request|response) +/// * [get sites](struct.SiteGetCall.html) (response) +/// * [patch sites](struct.SitePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Site { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#site". + pub kind: Option, + /// Subaccount ID of this site. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Name of this site.This is a required field. Must be less than 128 characters long. If this site is under a subaccount, the name must be unique among sites of the same subaccount. Otherwise, this site is a top-level site, and the name must be unique among top-level sites of the same account. + pub name: Option, + /// Dimension value for the ID of the directory site. This is a read-only, auto-generated field. + #[serde(alias="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Site-wide settings. + #[serde(alias="siteSettings")] + pub site_settings: Option, + /// ID of this site. This is a read-only, auto-generated field. + pub id: Option, + /// Directory site associated with this site. This is a required field that is read-only after insertion. + #[serde(alias="directorySiteId")] + pub directory_site_id: Option, + /// Site contacts. + #[serde(alias="siteContacts")] + pub site_contacts: Option>, + /// Key name of this site. This is a read-only, auto-generated field. + #[serde(alias="keyName")] + pub key_name: Option, + /// Dimension value for the ID of this site. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Whether this site is approved. + pub approved: Option, + /// Account ID of this site. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, +} + +impl RequestValue for Site {} +impl Resource for Site {} +impl ResponseResult for Site {} + + +/// DFP Settings +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DfpSettings { + /// DFP network name for this directory site. + pub dfp_network_name: String, + /// DFP network code for this directory site. + pub dfp_network_code: String, + /// Whether this directory site is available only via Publisher Portal. + #[serde(alias="publisherPortalOnly")] + pub publisher_portal_only: bool, + /// Whether this directory site accepts programmatic placements. + #[serde(alias="programmaticPlacementAccepted")] + pub programmatic_placement_accepted: bool, + /// Whether this directory site accepts publisher-paid tags. + #[serde(alias="pubPaidPlacementAccepted")] + pub pub_paid_placement_accepted: bool, +} + +impl Part for DfpSettings {} + + +/// Connection Type List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list connection types](struct.ConnectionTypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ConnectionTypesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#connectionTypesListResponse". + pub kind: String, + /// Connection Type Collection. + #[serde(alias="connectionTypes")] + pub connection_types: Vec, +} + +impl ResponseResult for ConnectionTypesListResponse {} + + +/// Contains properties of a Floodlight configuration. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get floodlight configurations](struct.FloodlightConfigurationGetCall.html) (response) +/// * [update floodlight configurations](struct.FloodlightConfigurationUpdateCall.html) (request|response) +/// * [patch floodlight configurations](struct.FloodlightConfigurationPatchCall.html) (request|response) +/// * [list floodlight configurations](struct.FloodlightConfigurationListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FloodlightConfiguration { + /// List of user defined variables enabled for this configuration. + #[serde(alias="userDefinedVariableConfigurations")] + pub user_defined_variable_configurations: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightConfiguration". + pub kind: Option, + /// Advertiser ID of the parent advertiser of this floodlight configuration. + #[serde(alias="advertiserId")] + pub advertiser_id: Option, + /// Configuration settings for dynamic and image floodlight tags. + #[serde(alias="tagSettings")] + pub tag_settings: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(alias="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of this floodlight configuration. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this floodlight configuration. This is a read-only field that can be left blank. + #[serde(alias="accountId")] + pub account_id: Option, + /// Types of attribution options for natural search conversions. + #[serde(alias="naturalSearchConversionAttributionOption")] + pub natural_search_conversion_attribution_option: Option, + /// Settings for DCM Omniture integration. + #[serde(alias="omnitureSettings")] + pub omniture_settings: Option, + /// Whether the exposure-to-conversion report is enabled. This report shows detailed pathway information on up to 10 of the most recent ad exposures seen by a user before converting. + #[serde(alias="exposureToConversionEnabled")] + pub exposure_to_conversion_enabled: Option, + /// Lookback window settings for this floodlight configuration. + #[serde(alias="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Day that will be counted as the first day of the week in reports. This is a required field. + #[serde(alias="firstDayOfWeek")] + pub first_day_of_week: Option, + /// List of standard variables enabled for this configuration. + /// + /// Acceptable values are: + /// - "ORD" + /// - "NUM" + #[serde(alias="standardVariableTypes")] + pub standard_variable_types: Option>, + /// Subaccount ID of this floodlight configuration. This is a read-only field that can be left blank. + #[serde(alias="subaccountId")] + pub subaccount_id: Option, + /// Whether advertiser data is shared with Google Analytics. + #[serde(alias="analyticsDataSharingEnabled")] + pub analytics_data_sharing_enabled: Option, + /// Dimension value for the ID of this floodlight configuration. This is a read-only, auto-generated field. + #[serde(alias="idDimensionValue")] + pub id_dimension_value: Option, + /// Whether floodlight activities owned by this configuration are required to be SSL-compliant. + #[serde(alias="sslRequired")] + pub ssl_required: Option, +} + +impl RequestValue for FloodlightConfiguration {} +impl Resource for FloodlightConfiguration {} +impl ResponseResult for FloodlightConfiguration {} + + +/// Represents a date range. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DateRange { + /// The start date of the date range, inclusive. A string of the format: "yyyy-MM-dd". + #[serde(alias="startDate")] + pub start_date: String, + /// The kind of resource this is, in this case dfareporting#dateRange. + pub kind: String, + /// The end date of the date range, inclusive. A string of the format: "yyyy-MM-dd". + #[serde(alias="endDate")] + pub end_date: String, + /// The date range relative to the date of when the report is run. + #[serde(alias="relativeDateRange")] + pub relative_date_range: String, +} + +impl Part for DateRange {} + + +/// Account Permission Group List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list account permission groups](struct.AccountPermissionGroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AccountPermissionGroupsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionGroupsListResponse". + pub kind: String, + /// Account permission group collection + #[serde(alias="accountPermissionGroups")] + pub account_permission_groups: Vec, +} + +impl ResponseResult for AccountPermissionGroupsListResponse {} + + +/// Size List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list sizes](struct.SizeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SizesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#sizesListResponse". + pub kind: String, + /// Size collection + pub sizes: Vec, +} + +impl ResponseResult for SizesListResponse {} + + +/// User Role List Response +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list user roles](struct.UserRoleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UserRolesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolesListResponse". + pub kind: String, + /// User role collection + #[serde(alias="userRoles")] + pub user_roles: Vec, +} + +impl ResponseResult for UserRolesListResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *userRolePermissionGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.user_role_permission_groups(); +/// # } +/// ``` +pub struct UserRolePermissionGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserRolePermissionGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one user role permission group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRolePermissionGroupGetCall<'a, C, NC, A> { + UserRolePermissionGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a list of all supported user role permission groups. + pub fn list(&self, profile_id: &str) -> UserRolePermissionGroupListCall<'a, C, NC, A> { + UserRolePermissionGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *platformType* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.platform_types(); +/// # } +/// ``` +pub struct PlatformTypeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PlatformTypeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlatformTypeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of platform types. + pub fn list(&self, profile_id: &str) -> PlatformTypeListCall<'a, C, NC, A> { + PlatformTypeListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creativeField* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.creative_fields(); +/// # } +/// ``` +pub struct CreativeFieldMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeFieldMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field. + pub fn update(&self, request: &CreativeField, profile_id: &str) -> CreativeFieldUpdateCall<'a, C, NC, A> { + CreativeFieldUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of creative fields, possibly filtered. + pub fn list(&self, profile_id: &str) -> CreativeFieldListCall<'a, C, NC, A> { + CreativeFieldListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _advertiser_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing creative field. + pub fn delete(&self, profile_id: &str, id: &str) -> CreativeFieldDeleteCall<'a, C, NC, A> { + CreativeFieldDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one creative field by ID. + pub fn get(&self, profile_id: &str, id: &str) -> CreativeFieldGetCall<'a, C, NC, A> { + CreativeFieldGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative field. + pub fn insert(&self, request: &CreativeField, profile_id: &str) -> CreativeFieldInsertCall<'a, C, NC, A> { + CreativeFieldInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field. This method supports patch semantics. + pub fn patch(&self, request: &CreativeField, profile_id: &str, id: &str) -> CreativeFieldPatchCall<'a, C, NC, A> { + CreativeFieldPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *userRole* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.user_roles(); +/// # } +/// ``` +pub struct UserRoleMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserRoleMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new user role. + pub fn insert(&self, request: &UserRole, profile_id: &str) -> UserRoleInsertCall<'a, C, NC, A> { + UserRoleInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one user role by ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRoleGetCall<'a, C, NC, A> { + UserRoleGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing user role. + pub fn update(&self, request: &UserRole, profile_id: &str) -> UserRoleUpdateCall<'a, C, NC, A> { + UserRoleUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing user role. + pub fn delete(&self, profile_id: &str, id: &str) -> UserRoleDeleteCall<'a, C, NC, A> { + UserRoleDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing user role. This method supports patch semantics. + pub fn patch(&self, request: &UserRole, profile_id: &str, id: &str) -> UserRolePatchCall<'a, C, NC, A> { + UserRolePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of user roles, possibly filtered. + pub fn list(&self, profile_id: &str) -> UserRoleListCall<'a, C, NC, A> { + UserRoleListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _subaccount_id: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _account_user_role_only: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *operatingSystemVersion* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.operating_system_versions(); +/// # } +/// ``` +pub struct OperatingSystemVersionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for OperatingSystemVersionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperatingSystemVersionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of operating system versions. + pub fn list(&self, profile_id: &str) -> OperatingSystemVersionListCall<'a, C, NC, A> { + OperatingSystemVersionListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *landingPage* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.landing_pages(); +/// # } +/// ``` +pub struct LandingPageMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for LandingPageMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one campaign landing page by ID. + pub fn get(&self, profile_id: &str, campaign_id: &str, id: &str) -> LandingPageGetCall<'a, C, NC, A> { + LandingPageGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing campaign landing page. + pub fn update(&self, request: &LandingPage, profile_id: &str, campaign_id: &str) -> LandingPageUpdateCall<'a, C, NC, A> { + LandingPageUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of landing pages for the specified campaign. + pub fn list(&self, profile_id: &str, campaign_id: &str) -> LandingPageListCall<'a, C, NC, A> { + LandingPageListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new landing page for the specified campaign. + pub fn insert(&self, request: &LandingPage, profile_id: &str, campaign_id: &str) -> LandingPageInsertCall<'a, C, NC, A> { + LandingPageInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing campaign landing page. This method supports patch semantics. + pub fn patch(&self, request: &LandingPage, profile_id: &str, campaign_id: &str, id: &str) -> LandingPagePatchCall<'a, C, NC, A> { + LandingPagePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing campaign landing page. + pub fn delete(&self, profile_id: &str, campaign_id: &str, id: &str) -> LandingPageDeleteCall<'a, C, NC, A> { + LandingPageDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *campaignCreativeAssociation* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.campaign_creative_associations(); +/// # } +/// ``` +pub struct CampaignCreativeAssociationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CampaignCreativeAssociationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignCreativeAssociationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Associates a creative with the specified campaign. This method creates a default ad with dimensions matching the creative in the campaign if such a default ad does not exist already. + pub fn insert(&self, request: &CampaignCreativeAssociation, profile_id: &str, campaign_id: &str) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> { + CampaignCreativeAssociationInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of creative IDs associated with the specified campaign. + pub fn list(&self, profile_id: &str, campaign_id: &str) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + CampaignCreativeAssociationListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _campaign_id: campaign_id.to_string(), + _sort_order: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *changeLog* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.change_logs(); +/// # } +/// ``` +pub struct ChangeLogMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChangeLogMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeLogMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of change logs. + pub fn list(&self, profile_id: &str) -> ChangeLogListCall<'a, C, NC, A> { + ChangeLogListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _user_profile_ids: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _object_type: Default::default(), + _object_ids: Default::default(), + _min_change_time: Default::default(), + _max_results: Default::default(), + _max_change_time: Default::default(), + _ids: Default::default(), + _action: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one change log by ID. + pub fn get(&self, profile_id: &str, id: &str) -> ChangeLogGetCall<'a, C, NC, A> { + ChangeLogGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one account by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountGetCall<'a, C, NC, A> { + AccountGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of accounts, possibly filtered. + pub fn list(&self, profile_id: &str) -> AccountListCall<'a, C, NC, A> { + AccountListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _active: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account. + pub fn update(&self, request: &Account, profile_id: &str) -> AccountUpdateCall<'a, C, NC, A> { + AccountUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account. This method supports patch semantics. + pub fn patch(&self, request: &Account, profile_id: &str, id: &str) -> AccountPatchCall<'a, C, NC, A> { + AccountPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *postalCode* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.postal_codes(); +/// # } +/// ``` +pub struct PostalCodeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PostalCodeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostalCodeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of postal codes. + pub fn list(&self, profile_id: &str) -> PostalCodeListCall<'a, C, NC, A> { + PostalCodeListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *advertiser* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.advertisers(); +/// # } +/// ``` +pub struct AdvertiserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdvertiserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new advertiser. + pub fn insert(&self, request: &Advertiser, profile_id: &str) -> AdvertiserInsertCall<'a, C, NC, A> { + AdvertiserInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing advertiser. This method supports patch semantics. + pub fn patch(&self, request: &Advertiser, profile_id: &str, id: &str) -> AdvertiserPatchCall<'a, C, NC, A> { + AdvertiserPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of advertisers, possibly filtered. + pub fn list(&self, profile_id: &str) -> AdvertiserListCall<'a, C, NC, A> { + AdvertiserListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _subaccount_id: Default::default(), + _status: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _only_parent: Default::default(), + _max_results: Default::default(), + _include_advertisers_without_groups_only: Default::default(), + _ids: Default::default(), + _floodlight_configuration_ids: Default::default(), + _advertiser_group_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing advertiser. + pub fn update(&self, request: &Advertiser, profile_id: &str) -> AdvertiserUpdateCall<'a, C, NC, A> { + AdvertiserUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one advertiser by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdvertiserGetCall<'a, C, NC, A> { + AdvertiserGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *dimensionValue* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `query(...)` +/// // to build up your call. +/// let rb = hub.dimension_values(); +/// # } +/// ``` +pub struct DimensionValueMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DimensionValueMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DimensionValueMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves list of report dimension values for a list of filters. + pub fn query(&self, request: &DimensionValueRequest, profile_id: &str) -> DimensionValueQueryCall<'a, C, NC, A> { + DimensionValueQueryCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *floodlightActivityGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.floodlight_activity_groups(); +/// # } +/// ``` +pub struct FloodlightActivityGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FloodlightActivityGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing floodlight activity group. + pub fn delete(&self, profile_id: &str, id: &str) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> { + FloodlightActivityGroupDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one floodlight activity group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightActivityGroupGetCall<'a, C, NC, A> { + FloodlightActivityGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight activity group. This method supports patch semantics. + pub fn patch(&self, request: &FloodlightActivityGroup, profile_id: &str, id: &str) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> { + FloodlightActivityGroupPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of floodlight activity groups, possibly filtered. + pub fn list(&self, profile_id: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + FloodlightActivityGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _type_: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _floodlight_configuration_id: Default::default(), + _advertiser_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new floodlight activity group. + pub fn insert(&self, request: &FloodlightActivityGroup, profile_id: &str) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> { + FloodlightActivityGroupInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight activity group. + pub fn update(&self, request: &FloodlightActivityGroup, profile_id: &str) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> { + FloodlightActivityGroupUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *metro* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.metros(); +/// # } +/// ``` +pub struct MetroMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MetroMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetroMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of metros. + pub fn list(&self, profile_id: &str) -> MetroListCall<'a, C, NC, A> { + MetroListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *directorySiteContact* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.directory_site_contacts(); +/// # } +/// ``` +pub struct DirectorySiteContactMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DirectorySiteContactMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteContactMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one directory site contact by ID. + pub fn get(&self, profile_id: &str, id: &str) -> DirectorySiteContactGetCall<'a, C, NC, A> { + DirectorySiteContactGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of directory site contacts, possibly filtered. + pub fn list(&self, profile_id: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + DirectorySiteContactListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _directory_site_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *userProfile* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.user_profiles(); +/// # } +/// ``` +pub struct UserProfileMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserProfileMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserProfileMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves list of user profiles for a user. + pub fn list(&self) -> UserProfileListCall<'a, C, NC, A> { + UserProfileListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one user profile by ID. + pub fn get(&self, profile_id: &str) -> UserProfileGetCall<'a, C, NC, A> { + UserProfileGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *ad* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.ads(); +/// # } +/// ``` +pub struct AdMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing ad. This method supports patch semantics. + pub fn patch(&self, request: &Ad, profile_id: &str, id: &str) -> AdPatchCall<'a, C, NC, A> { + AdPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new ad. + pub fn insert(&self, request: &Ad, profile_id: &str) -> AdInsertCall<'a, C, NC, A> { + AdInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of ads, possibly filtered. + pub fn list(&self, profile_id: &str) -> AdListCall<'a, C, NC, A> { + AdListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _type_: Default::default(), + _ssl_required: Default::default(), + _ssl_compliant: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _size_ids: Default::default(), + _search_string: Default::default(), + _remarketing_list_ids: Default::default(), + _placement_ids: Default::default(), + _page_token: Default::default(), + _overridden_event_tag_id: Default::default(), + _max_results: Default::default(), + _landing_page_ids: Default::default(), + _ids: Default::default(), + _dynamic_click_tracker: Default::default(), + _creative_type: Default::default(), + _creative_optimization_configuration_ids: Default::default(), + _creative_ids: Default::default(), + _compatibility: Default::default(), + _campaign_ids: Default::default(), + _audience_segment_ids: Default::default(), + _archived: Default::default(), + _advertiser_id: Default::default(), + _active: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one ad by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdGetCall<'a, C, NC, A> { + AdGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing ad. + pub fn update(&self, request: &Ad, profile_id: &str) -> AdUpdateCall<'a, C, NC, A> { + AdUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountPermission* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.account_permissions(); +/// # } +/// ``` +pub struct AccountPermissionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountPermissionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one account permission by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountPermissionGetCall<'a, C, NC, A> { + AccountPermissionGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of account permissions. + pub fn list(&self, profile_id: &str) -> AccountPermissionListCall<'a, C, NC, A> { + AccountPermissionListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *connectionType* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.connection_types(); +/// # } +/// ``` +pub struct ConnectionTypeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ConnectionTypeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConnectionTypeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of connection types. + pub fn list(&self, profile_id: &str) -> ConnectionTypeListCall<'a, C, NC, A> { + ConnectionTypeListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *advertiserGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.advertiser_groups(); +/// # } +/// ``` +pub struct AdvertiserGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AdvertiserGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one advertiser group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdvertiserGroupGetCall<'a, C, NC, A> { + AdvertiserGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of advertiser groups, possibly filtered. + pub fn list(&self, profile_id: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + AdvertiserGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new advertiser group. + pub fn insert(&self, request: &AdvertiserGroup, profile_id: &str) -> AdvertiserGroupInsertCall<'a, C, NC, A> { + AdvertiserGroupInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing advertiser group. + pub fn update(&self, request: &AdvertiserGroup, profile_id: &str) -> AdvertiserGroupUpdateCall<'a, C, NC, A> { + AdvertiserGroupUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing advertiser group. This method supports patch semantics. + pub fn patch(&self, request: &AdvertiserGroup, profile_id: &str, id: &str) -> AdvertiserGroupPatchCall<'a, C, NC, A> { + AdvertiserGroupPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing advertiser group. + pub fn delete(&self, profile_id: &str, id: &str) -> AdvertiserGroupDeleteCall<'a, C, NC, A> { + AdvertiserGroupDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *site* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.sites(); +/// # } +/// ``` +pub struct SiteMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SiteMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SiteMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new site. + pub fn insert(&self, request: &Site, profile_id: &str) -> SiteInsertCall<'a, C, NC, A> { + SiteInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one site by ID. + pub fn get(&self, profile_id: &str, id: &str) -> SiteGetCall<'a, C, NC, A> { + SiteGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of sites, possibly filtered. + pub fn list(&self, profile_id: &str) -> SiteListCall<'a, C, NC, A> { + SiteListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _unmapped_site: Default::default(), + _subaccount_id: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _directory_site_ids: Default::default(), + _campaign_ids: Default::default(), + _approved: Default::default(), + _ad_words_site: Default::default(), + _accepts_publisher_paid_placements: Default::default(), + _accepts_interstitial_placements: Default::default(), + _accepts_in_stream_video_placements: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing site. + pub fn update(&self, request: &Site, profile_id: &str) -> SiteUpdateCall<'a, C, NC, A> { + SiteUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing site. This method supports patch semantics. + pub fn patch(&self, request: &Site, profile_id: &str, id: &str) -> SitePatchCall<'a, C, NC, A> { + SitePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *floodlightActivity* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `generatetag(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.floodlight_activities(); +/// # } +/// ``` +pub struct FloodlightActivityMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FloodlightActivityMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one floodlight activity by ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightActivityGetCall<'a, C, NC, A> { + FloodlightActivityGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of floodlight activities, possibly filtered. + pub fn list(&self, profile_id: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + FloodlightActivityListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _tag_string: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _floodlight_configuration_id: Default::default(), + _floodlight_activity_group_type: Default::default(), + _floodlight_activity_group_tag_string: Default::default(), + _floodlight_activity_group_name: Default::default(), + _floodlight_activity_group_ids: Default::default(), + _advertiser_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new floodlight activity. + pub fn insert(&self, request: &FloodlightActivity, profile_id: &str) -> FloodlightActivityInsertCall<'a, C, NC, A> { + FloodlightActivityInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing floodlight activity. + pub fn delete(&self, profile_id: &str, id: &str) -> FloodlightActivityDeleteCall<'a, C, NC, A> { + FloodlightActivityDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight activity. This method supports patch semantics. + pub fn patch(&self, request: &FloodlightActivity, profile_id: &str, id: &str) -> FloodlightActivityPatchCall<'a, C, NC, A> { + FloodlightActivityPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generates a tag for a floodlight activity. + pub fn generatetag(&self, profile_id: &str) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> { + FloodlightActivityGeneratetagCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _floodlight_activity_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight activity. + pub fn update(&self, request: &FloodlightActivity, profile_id: &str) -> FloodlightActivityUpdateCall<'a, C, NC, A> { + FloodlightActivityUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *region* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.regions(); +/// # } +/// ``` +pub struct RegionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RegionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of regions. + pub fn list(&self, profile_id: &str) -> RegionListCall<'a, C, NC, A> { + RegionListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creativeGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.creative_groups(); +/// # } +/// ``` +pub struct CreativeGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative group. + pub fn insert(&self, request: &CreativeGroup, profile_id: &str) -> CreativeGroupInsertCall<'a, C, NC, A> { + CreativeGroupInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one creative group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> CreativeGroupGetCall<'a, C, NC, A> { + CreativeGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative group. + pub fn update(&self, request: &CreativeGroup, profile_id: &str) -> CreativeGroupUpdateCall<'a, C, NC, A> { + CreativeGroupUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of creative groups, possibly filtered. + pub fn list(&self, profile_id: &str) -> CreativeGroupListCall<'a, C, NC, A> { + CreativeGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _group_number: Default::default(), + _advertiser_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative group. This method supports patch semantics. + pub fn patch(&self, request: &CreativeGroup, profile_id: &str, id: &str) -> CreativeGroupPatchCall<'a, C, NC, A> { + CreativeGroupPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *subaccount* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.subaccounts(); +/// # } +/// ``` +pub struct SubaccountMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SubaccountMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing subaccount. This method supports patch semantics. + pub fn patch(&self, request: &Subaccount, profile_id: &str, id: &str) -> SubaccountPatchCall<'a, C, NC, A> { + SubaccountPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new subaccount. + pub fn insert(&self, request: &Subaccount, profile_id: &str) -> SubaccountInsertCall<'a, C, NC, A> { + SubaccountInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a list of subaccounts, possibly filtered. + pub fn list(&self, profile_id: &str) -> SubaccountListCall<'a, C, NC, A> { + SubaccountListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing subaccount. + pub fn update(&self, request: &Subaccount, profile_id: &str) -> SubaccountUpdateCall<'a, C, NC, A> { + SubaccountUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one subaccount by ID. + pub fn get(&self, profile_id: &str, id: &str) -> SubaccountGetCall<'a, C, NC, A> { + SubaccountGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *mobileCarrier* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.mobile_carriers(); +/// # } +/// ``` +pub struct MobileCarrierMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MobileCarrierMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobileCarrierMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of mobile carriers. + pub fn list(&self, profile_id: &str) -> MobileCarrierListCall<'a, C, NC, A> { + MobileCarrierListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *floodlightConfiguration* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.floodlight_configurations(); +/// # } +/// ``` +pub struct FloodlightConfigurationMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FloodlightConfigurationMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightConfigurationMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight configuration. + pub fn update(&self, request: &FloodlightConfiguration, profile_id: &str) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> { + FloodlightConfigurationUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing floodlight configuration. This method supports patch semantics. + pub fn patch(&self, request: &FloodlightConfiguration, profile_id: &str, id: &str) -> FloodlightConfigurationPatchCall<'a, C, NC, A> { + FloodlightConfigurationPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one floodlight configuration by ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightConfigurationGetCall<'a, C, NC, A> { + FloodlightConfigurationGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of floodlight configurations, possibly filtered. + pub fn list(&self, profile_id: &str) -> FloodlightConfigurationListCall<'a, C, NC, A> { + FloodlightConfigurationListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *operatingSystem* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.operating_systems(); +/// # } +/// ``` +pub struct OperatingSystemMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for OperatingSystemMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperatingSystemMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of operating systems. + pub fn list(&self, profile_id: &str) -> OperatingSystemListCall<'a, C, NC, A> { + OperatingSystemListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *file* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.files(); +/// # } +/// ``` +pub struct FileMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FileMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists files for a user profile. + pub fn list(&self, profile_id: &str) -> FileListCall<'a, C, NC, A> { + FileListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _scope: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a report file by its report ID and file ID. + pub fn get(&self, report_id: &str, file_id: &str) -> FileGetCall<'a, C, NC, A> { + FileGetCall { + hub: self.hub, + _report_id: report_id.to_string(), + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *placementGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.placement_groups(); +/// # } +/// ``` +pub struct PlacementGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PlacementGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of placement groups, possibly filtered. + pub fn list(&self, profile_id: &str) -> PlacementGroupListCall<'a, C, NC, A> { + PlacementGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _site_ids: Default::default(), + _search_string: Default::default(), + _pricing_types: Default::default(), + _placement_strategy_ids: Default::default(), + _placement_group_type: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _directory_site_ids: Default::default(), + _content_category_ids: Default::default(), + _campaign_ids: Default::default(), + _archived: Default::default(), + _advertiser_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement group. + pub fn update(&self, request: &PlacementGroup, profile_id: &str) -> PlacementGroupUpdateCall<'a, C, NC, A> { + PlacementGroupUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new placement group. + pub fn insert(&self, request: &PlacementGroup, profile_id: &str) -> PlacementGroupInsertCall<'a, C, NC, A> { + PlacementGroupInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one placement group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementGroupGetCall<'a, C, NC, A> { + PlacementGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement group. This method supports patch semantics. + pub fn patch(&self, request: &PlacementGroup, profile_id: &str, id: &str) -> PlacementGroupPatchCall<'a, C, NC, A> { + PlacementGroupPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creativeAsset* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `insert(...)` +/// // to build up your call. +/// let rb = hub.creative_assets(); +/// # } +/// ``` +pub struct CreativeAssetMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeAssetMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeAssetMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative asset. + pub fn insert(&self, request: &CreativeAssetMetadata, profile_id: &str, advertiser_id: &str) -> CreativeAssetInsertCall<'a, C, NC, A> { + CreativeAssetInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _advertiser_id: advertiser_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *userRolePermission* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.user_role_permissions(); +/// # } +/// ``` +pub struct UserRolePermissionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserRolePermissionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one user role permission by ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRolePermissionGetCall<'a, C, NC, A> { + UserRolePermissionGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a list of user role permissions, possibly filtered. + pub fn list(&self, profile_id: &str) -> UserRolePermissionListCall<'a, C, NC, A> { + UserRolePermissionListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountPermissionGroup* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.account_permission_groups(); +/// # } +/// ``` +pub struct AccountPermissionGroupMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountPermissionGroupMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionGroupMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of account permission groups. + pub fn list(&self, profile_id: &str) -> AccountPermissionGroupListCall<'a, C, NC, A> { + AccountPermissionGroupListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one account permission group by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountPermissionGroupGetCall<'a, C, NC, A> { + AccountPermissionGroupGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *contentCategory* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.content_categories(); +/// # } +/// ``` +pub struct ContentCategoryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ContentCategoryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of content categories, possibly filtered. + pub fn list(&self, profile_id: &str) -> ContentCategoryListCall<'a, C, NC, A> { + ContentCategoryListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing content category. + pub fn update(&self, request: &ContentCategory, profile_id: &str) -> ContentCategoryUpdateCall<'a, C, NC, A> { + ContentCategoryUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new content category. + pub fn insert(&self, request: &ContentCategory, profile_id: &str) -> ContentCategoryInsertCall<'a, C, NC, A> { + ContentCategoryInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing content category. + pub fn delete(&self, profile_id: &str, id: &str) -> ContentCategoryDeleteCall<'a, C, NC, A> { + ContentCategoryDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one content category by ID. + pub fn get(&self, profile_id: &str, id: &str) -> ContentCategoryGetCall<'a, C, NC, A> { + ContentCategoryGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing content category. This method supports patch semantics. + pub fn patch(&self, request: &ContentCategory, profile_id: &str, id: &str) -> ContentCategoryPatchCall<'a, C, NC, A> { + ContentCategoryPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creative* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.creatives(); +/// # } +/// ``` +pub struct CreativeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative. + pub fn insert(&self, request: &Creative, profile_id: &str) -> CreativeInsertCall<'a, C, NC, A> { + CreativeInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative. + pub fn update(&self, request: &Creative, profile_id: &str) -> CreativeUpdateCall<'a, C, NC, A> { + CreativeUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one creative by ID. + pub fn get(&self, profile_id: &str, id: &str) -> CreativeGetCall<'a, C, NC, A> { + CreativeGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of creatives, possibly filtered. + pub fn list(&self, profile_id: &str) -> CreativeListCall<'a, C, NC, A> { + CreativeListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _types: Default::default(), + _studio_creative_id: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _size_ids: Default::default(), + _search_string: Default::default(), + _rendering_ids: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _creative_field_ids: Default::default(), + _companion_creative_ids: Default::default(), + _campaign_id: Default::default(), + _archived: Default::default(), + _advertiser_id: Default::default(), + _active: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative. This method supports patch semantics. + pub fn patch(&self, request: &Creative, profile_id: &str, id: &str) -> CreativePatchCall<'a, C, NC, A> { + CreativePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *campaign* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.campaigns(); +/// # } +/// ``` +pub struct CampaignMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CampaignMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one campaign by ID. + pub fn get(&self, profile_id: &str, id: &str) -> CampaignGetCall<'a, C, NC, A> { + CampaignGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new campaign. + pub fn insert(&self, request: &Campaign, profile_id: &str, default_landing_page_name: &str, default_landing_page_url: &str) -> CampaignInsertCall<'a, C, NC, A> { + CampaignInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _default_landing_page_name: default_landing_page_name.to_string(), + _default_landing_page_url: default_landing_page_url.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing campaign. This method supports patch semantics. + pub fn patch(&self, request: &Campaign, profile_id: &str, id: &str) -> CampaignPatchCall<'a, C, NC, A> { + CampaignPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing campaign. + pub fn update(&self, request: &Campaign, profile_id: &str) -> CampaignUpdateCall<'a, C, NC, A> { + CampaignUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of campaigns, possibly filtered. + pub fn list(&self, profile_id: &str) -> CampaignListCall<'a, C, NC, A> { + CampaignListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _subaccount_id: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _overridden_event_tag_id: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _excluded_ids: Default::default(), + _at_least_one_optimization_activity: Default::default(), + _archived: Default::default(), + _advertiser_ids: Default::default(), + _advertiser_group_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *eventTag* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.event_tags(); +/// # } +/// ``` +pub struct EventTagMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for EventTagMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing event tag. + pub fn delete(&self, profile_id: &str, id: &str) -> EventTagDeleteCall<'a, C, NC, A> { + EventTagDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of event tags, possibly filtered. + pub fn list(&self, profile_id: &str) -> EventTagListCall<'a, C, NC, A> { + EventTagListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _ids: Default::default(), + _event_tag_types: Default::default(), + _enabled: Default::default(), + _definitions_only: Default::default(), + _campaign_id: Default::default(), + _advertiser_id: Default::default(), + _ad_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new event tag. + pub fn insert(&self, request: &EventTag, profile_id: &str) -> EventTagInsertCall<'a, C, NC, A> { + EventTagInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing event tag. This method supports patch semantics. + pub fn patch(&self, request: &EventTag, profile_id: &str, id: &str) -> EventTagPatchCall<'a, C, NC, A> { + EventTagPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing event tag. + pub fn update(&self, request: &EventTag, profile_id: &str) -> EventTagUpdateCall<'a, C, NC, A> { + EventTagUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one event tag by ID. + pub fn get(&self, profile_id: &str, id: &str) -> EventTagGetCall<'a, C, NC, A> { + EventTagGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *city* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.cities(); +/// # } +/// ``` +pub struct CityMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CityMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CityMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of cities, possibly filtered. + pub fn list(&self, profile_id: &str) -> CityListCall<'a, C, NC, A> { + CityListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _region_dart_ids: Default::default(), + _name_prefix: Default::default(), + _dart_ids: Default::default(), + _country_dart_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *placementStrategy* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.placement_strategies(); +/// # } +/// ``` +pub struct PlacementStrategyMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PlacementStrategyMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of placement strategies, possibly filtered. + pub fn list(&self, profile_id: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + PlacementStrategyListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement strategy. + pub fn update(&self, request: &PlacementStrategy, profile_id: &str) -> PlacementStrategyUpdateCall<'a, C, NC, A> { + PlacementStrategyUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one placement strategy by ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementStrategyGetCall<'a, C, NC, A> { + PlacementStrategyGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing placement strategy. + pub fn delete(&self, profile_id: &str, id: &str) -> PlacementStrategyDeleteCall<'a, C, NC, A> { + PlacementStrategyDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new placement strategy. + pub fn insert(&self, request: &PlacementStrategy, profile_id: &str) -> PlacementStrategyInsertCall<'a, C, NC, A> { + PlacementStrategyInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement strategy. This method supports patch semantics. + pub fn patch(&self, request: &PlacementStrategy, profile_id: &str, id: &str) -> PlacementStrategyPatchCall<'a, C, NC, A> { + PlacementStrategyPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *directorySite* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.directory_sites(); +/// # } +/// ``` +pub struct DirectorySiteMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for DirectorySiteMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of directory sites, possibly filtered. + pub fn list(&self, profile_id: &str) -> DirectorySiteListCall<'a, C, NC, A> { + DirectorySiteListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _parent_id: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _dfp_network_code: Default::default(), + _country_id: Default::default(), + _active: Default::default(), + _accepts_publisher_paid_placements: Default::default(), + _accepts_interstitial_placements: Default::default(), + _accepts_in_stream_video_placements: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one directory site by ID. + pub fn get(&self, profile_id: &str, id: &str) -> DirectorySiteGetCall<'a, C, NC, A> { + DirectorySiteGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *size* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.sizes(); +/// # } +/// ``` +pub struct SizeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SizeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SizeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new size. + pub fn insert(&self, request: &Size, profile_id: &str) -> SizeInsertCall<'a, C, NC, A> { + SizeInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of sizes, possibly filtered. + pub fn list(&self, profile_id: &str) -> SizeListCall<'a, C, NC, A> { + SizeListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _width: Default::default(), + _ids: Default::default(), + _iab_standard: Default::default(), + _height: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one size by ID. + pub fn get(&self, profile_id: &str, id: &str) -> SizeGetCall<'a, C, NC, A> { + SizeGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountActiveAdSummary* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.account_active_ad_summaries(); +/// # } +/// ``` +pub struct AccountActiveAdSummaryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountActiveAdSummaryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountActiveAdSummaryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the account's active ad summary by account ID. + pub fn get(&self, profile_id: &str, summary_account_id: &str) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> { + AccountActiveAdSummaryGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _summary_account_id: summary_account_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *accountUserProfile* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.account_user_profiles(); +/// # } +/// ``` +pub struct AccountUserProfileMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AccountUserProfileMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUserProfileMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account user profile. + pub fn update(&self, request: &AccountUserProfile, profile_id: &str) -> AccountUserProfileUpdateCall<'a, C, NC, A> { + AccountUserProfileUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of account user profiles, possibly filtered. + pub fn list(&self, profile_id: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + AccountUserProfileListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _user_role_id: Default::default(), + _subaccount_id: Default::default(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _active: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account user profile. This method supports patch semantics. + pub fn patch(&self, request: &AccountUserProfile, profile_id: &str, id: &str) -> AccountUserProfilePatchCall<'a, C, NC, A> { + AccountUserProfilePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one account user profile by ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountUserProfileGetCall<'a, C, NC, A> { + AccountUserProfileGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *country* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.countries(); +/// # } +/// ``` +pub struct CountryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CountryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CountryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of countries. + pub fn list(&self, profile_id: &str) -> CountryListCall<'a, C, NC, A> { + CountryListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one country by ID. + pub fn get(&self, profile_id: &str, dart_id: &str) -> CountryGetCall<'a, C, NC, A> { + CountryGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _dart_id: dart_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *creativeFieldValue* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.creative_field_values(); +/// # } +/// ``` +pub struct CreativeFieldValueMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CreativeFieldValueMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field value. This method supports patch semantics. + pub fn patch(&self, request: &CreativeFieldValue, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + CreativeFieldValuePatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing creative field value. + pub fn delete(&self, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValueDeleteCall<'a, C, NC, A> { + CreativeFieldValueDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative field value. + pub fn insert(&self, request: &CreativeFieldValue, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueInsertCall<'a, C, NC, A> { + CreativeFieldValueInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field value. + pub fn update(&self, request: &CreativeFieldValue, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueUpdateCall<'a, C, NC, A> { + CreativeFieldValueUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one creative field value by ID. + pub fn get(&self, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValueGetCall<'a, C, NC, A> { + CreativeFieldValueGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of creative field values, possibly filtered. + pub fn list(&self, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + CreativeFieldValueListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _creative_field_id: creative_field_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *report* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `compatible_fields_query(...)`, `delete(...)`, `files_get(...)`, `files_list(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `run(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.reports(); +/// # } +/// ``` +pub struct ReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates a report. + pub fn update(&self, request: &Report, profile_id: &str, report_id: &str) -> ReportUpdateCall<'a, C, NC, A> { + ReportUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Runs a report. + pub fn run(&self, profile_id: &str, report_id: &str) -> ReportRunCall<'a, C, NC, A> { + ReportRunCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _synchronous: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a report. This method supports patch semantics. + pub fn patch(&self, request: &Report, profile_id: &str, report_id: &str) -> ReportPatchCall<'a, C, NC, A> { + ReportPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists files for a report. + pub fn files_list(&self, profile_id: &str, report_id: &str) -> ReportFileListCall<'a, C, NC, A> { + ReportFileListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a report. + pub fn insert(&self, request: &Report, profile_id: &str) -> ReportInsertCall<'a, C, NC, A> { + ReportInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the fields that are compatible to be selected in the respective sections of a report criteria, given the fields already selected in the input report and user permissions. + pub fn compatible_fields_query(&self, request: &Report, profile_id: &str) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> { + ReportCompatibleFieldQueryCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a report by its ID. + pub fn get(&self, profile_id: &str, report_id: &str) -> ReportGetCall<'a, C, NC, A> { + ReportGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a report file. + pub fn files_get(&self, profile_id: &str, report_id: &str, file_id: &str) -> ReportFileGetCall<'a, C, NC, A> { + ReportFileGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a report by its ID. + pub fn delete(&self, profile_id: &str, report_id: &str) -> ReportDeleteCall<'a, C, NC, A> { + ReportDeleteCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _report_id: report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves list of reports. + pub fn list(&self, profile_id: &str) -> ReportListCall<'a, C, NC, A> { + ReportListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _scope: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *browser* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.browsers(); +/// # } +/// ``` +pub struct BrowserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for BrowserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> BrowserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of browsers. + pub fn list(&self, profile_id: &str) -> BrowserListCall<'a, C, NC, A> { + BrowserListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *placement* resources. +/// It is not used directly, but through the `Dfareporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dfareporting2" as dfareporting2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2::Dfareporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generatetags(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.placements(); +/// # } +/// ``` +pub struct PlacementMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PlacementMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement. This method supports patch semantics. + pub fn patch(&self, request: &Placement, profile_id: &str, id: &str) -> PlacementPatchCall<'a, C, NC, A> { + PlacementPatchCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of placements, possibly filtered. + pub fn list(&self, profile_id: &str) -> PlacementListCall<'a, C, NC, A> { + PlacementListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _size_ids: Default::default(), + _site_ids: Default::default(), + _search_string: Default::default(), + _pricing_types: Default::default(), + _placement_strategy_ids: Default::default(), + _payment_source: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _group_ids: Default::default(), + _directory_site_ids: Default::default(), + _content_category_ids: Default::default(), + _compatibilities: Default::default(), + _campaign_ids: Default::default(), + _archived: Default::default(), + _advertiser_ids: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one placement by ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementGetCall<'a, C, NC, A> { + PlacementGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new placement. + pub fn insert(&self, request: &Placement, profile_id: &str) -> PlacementInsertCall<'a, C, NC, A> { + PlacementInsertCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement. + pub fn update(&self, request: &Placement, profile_id: &str) -> PlacementUpdateCall<'a, C, NC, A> { + PlacementUpdateCall { + hub: self.hub, + _request: request.clone(), + _profile_id: profile_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generates tags for a placement. + pub fn generatetags(&self, profile_id: &str) -> PlacementGeneratetagCall<'a, C, NC, A> { + PlacementGeneratetagCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _tag_formats: Default::default(), + _placement_ids: Default::default(), + _campaign_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Gets one user role permission group by ID. +/// +/// A builder for the *get* method supported by a *userRolePermissionGroup* resource. +/// It is not used directly, but through a `UserRolePermissionGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_role_permission_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePermissionGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRolePermissionGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRolePermissionGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRolePermissionGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRolePermissionGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User role permission group ID. + pub fn id(mut self, new_value: &str) -> UserRolePermissionGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRolePermissionGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRolePermissionGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a list of all supported user role permission groups. +/// +/// A builder for the *list* method supported by a *userRolePermissionGroup* resource. +/// It is not used directly, but through a `UserRolePermissionGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_role_permission_groups().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePermissionGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRolePermissionGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRolePermissionGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRolePermissionGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRolePermissionGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRolePermissionGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRolePermissionGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of platform types. +/// +/// A builder for the *list* method supported by a *platformType* resource. +/// It is not used directly, but through a `PlatformTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.platform_types().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlatformTypeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlatformTypeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlatformTypeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlatformTypesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.platformTypes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/platformTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlatformTypeListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlatformTypeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlatformTypeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlatformTypeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative field. +/// +/// A builder for the *update* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeField = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeField, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeField)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeField) -> CreativeFieldUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of creative fields, possibly filtered. +/// +/// A builder for the *list* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().list("profileId") +/// .sort_order("et") +/// .sort_field("diam") +/// .search_string("ipsum") +/// .page_token("Lorem") +/// .max_results(-21) +/// .add_ids("duo") +/// .add_advertiser_ids("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _advertiser_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._advertiser_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserIds", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for creative fields by name or ID. Wildcards (*) are allowed. For example, "creativefield*2015" will return creative fields with names like "creativefield June 2015", "creativefield April 2015" or simply "creativefield 2015". Most of the searches also add wild-cards implicitly at the start and the end of the search string. For example, a search string of "creativefield" will match creative fields with the name "my creativefield", "creativefield 2015" or simply "creativefield". + pub fn search_string(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CreativeFieldListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creative fields with these IDs. + pub fn add_ids(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *advertiser ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creative fields that belong to these advertisers. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, NC, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing creative field. +/// +/// A builder for the *delete* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field ID + pub fn id(mut self, new_value: &str) -> CreativeFieldDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one creative field by ID. +/// +/// A builder for the *get* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeField)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field ID + pub fn id(mut self, new_value: &str) -> CreativeFieldGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new creative field. +/// +/// A builder for the *insert* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeField = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeField, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeField)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeField) -> CreativeFieldInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative field. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *creativeField* resource. +/// It is not used directly, but through a `CreativeFieldMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeField = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_fields().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeField, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeField)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFields.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeField) -> CreativeFieldPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field ID + pub fn id(mut self, new_value: &str) -> CreativeFieldPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new user role. +/// +/// A builder for the *insert* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserRole = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct UserRoleInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: UserRole, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRoleInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRole)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserRole) -> UserRoleInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRoleInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRoleInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRoleInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one user role by ID. +/// +/// A builder for the *get* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct UserRoleGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRoleGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRole)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRoleGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User role ID. + pub fn id(mut self, new_value: &str) -> UserRoleGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRoleGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRoleGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing user role. +/// +/// A builder for the *update* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserRole = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct UserRoleUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: UserRole, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRoleUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRole)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserRole) -> UserRoleUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRoleUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRoleUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRoleUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing user role. +/// +/// A builder for the *delete* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct UserRoleDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRoleDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRoleDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User role ID. + pub fn id(mut self, new_value: &str) -> UserRoleDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRoleDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRoleDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing user role. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UserRole = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: UserRole, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRolePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRole)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UserRole) -> UserRolePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRolePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User role ID. + pub fn id(mut self, new_value: &str) -> UserRolePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRolePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRolePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of user roles, possibly filtered. +/// +/// A builder for the *list* method supported by a *userRole* resource. +/// It is not used directly, but through a `UserRoleMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_roles().list("profileId") +/// .subaccount_id("Lorem") +/// .sort_order("sea") +/// .sort_field("et") +/// .search_string("duo") +/// .page_token("et") +/// .max_results(-40) +/// .add_ids("sanctus") +/// .account_user_role_only(true) +/// .doit(); +/// # } +/// ``` +pub struct UserRoleListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _subaccount_id: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _account_user_role_only: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRoleListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRoleListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRolesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRoles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._subaccount_id { + params.push(("subaccountId", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._account_user_role_only { + params.push(("accountUserRoleOnly", value.to_string())); + } + for &field in ["alt", "profileId", "subaccountId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "accountUserRoleOnly"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *subaccount id* query property to the given value. + /// + /// + /// Select only user roles that belong to this subaccount. + pub fn subaccount_id(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "userrole*2015" will return objects with names like "userrole June 2015", "userrole April 2015" or simply "userrole 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "userrole" will match objects with name "my userrole", "userrole 2015" or simply "userrole". + pub fn search_string(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> UserRoleListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only user roles with the specified IDs. + pub fn add_ids(mut self, new_value: &str) -> UserRoleListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *account user role only* query property to the given value. + /// + /// + /// Select only account level user roles not associated with any specific subaccount. + pub fn account_user_role_only(mut self, new_value: bool) -> UserRoleListCall<'a, C, NC, A> { + self._account_user_role_only = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRoleListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRoleListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of operating system versions. +/// +/// A builder for the *list* method supported by a *operatingSystemVersion* resource. +/// It is not used directly, but through a `OperatingSystemVersionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.operating_system_versions().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct OperatingSystemVersionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OperatingSystemVersionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperatingSystemVersionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperatingSystemVersionsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.operatingSystemVersions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/operatingSystemVersions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemVersionListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemVersionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperatingSystemVersionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperatingSystemVersionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one campaign landing page by ID. +/// +/// A builder for the *get* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().get("profileId", "campaignId", "id") +/// .doit(); +/// # } +/// ``` +pub struct LandingPageGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _campaign_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPageGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LandingPage)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "campaignId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["profileId", "campaignId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page ID. + pub fn id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPageGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPageGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing campaign landing page. +/// +/// A builder for the *update* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: LandingPage = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().update(&req, "profileId", "campaignId") +/// .doit(); +/// # } +/// ``` +pub struct LandingPageUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: LandingPage, + _profile_id: String, + _campaign_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPageUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LandingPage)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + for &field in ["alt", "profileId", "campaignId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &LandingPage) -> LandingPageUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPageUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageUpdateCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPageUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPageUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of landing pages for the specified campaign. +/// +/// A builder for the *list* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().list("profileId", "campaignId") +/// .doit(); +/// # } +/// ``` +pub struct LandingPageListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _campaign_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPageListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LandingPagesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + for &field in ["alt", "profileId", "campaignId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPageListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageListCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPageListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPageListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new landing page for the specified campaign. +/// +/// A builder for the *insert* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: LandingPage = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().insert(&req, "profileId", "campaignId") +/// .doit(); +/// # } +/// ``` +pub struct LandingPageInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: LandingPage, + _profile_id: String, + _campaign_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPageInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LandingPage)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + for &field in ["alt", "profileId", "campaignId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &LandingPage) -> LandingPageInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPageInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageInsertCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPageInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPageInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing campaign landing page. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: LandingPage = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().patch(&req, "profileId", "campaignId", "id") +/// .doit(); +/// # } +/// ``` +pub struct LandingPagePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: LandingPage, + _profile_id: String, + _campaign_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPagePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPagePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LandingPage)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "campaignId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &LandingPage) -> LandingPagePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page ID. + pub fn id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPagePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPagePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPagePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing campaign landing page. +/// +/// A builder for the *delete* method supported by a *landingPage* resource. +/// It is not used directly, but through a `LandingPageMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.landing_pages().delete("profileId", "campaignId", "id") +/// .doit(); +/// # } +/// ``` +pub struct LandingPageDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _campaign_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for LandingPageDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LandingPageDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.landingPages.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "campaignId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/landingPages/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["profileId", "campaignId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Landing page ID. + pub fn id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LandingPageDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LandingPageDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Associates a creative with the specified campaign. This method creates a default ad with dimensions matching the creative in the campaign if such a default ad does not exist already. +/// +/// A builder for the *insert* method supported by a *campaignCreativeAssociation* resource. +/// It is not used directly, but through a `CampaignCreativeAssociationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CampaignCreativeAssociation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CampaignCreativeAssociation = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaign_creative_associations().insert(&req, "profileId", "campaignId") +/// .doit(); +/// # } +/// ``` +pub struct CampaignCreativeAssociationInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CampaignCreativeAssociation, + _profile_id: String, + _campaign_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignCreativeAssociationInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignCreativeAssociationInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CampaignCreativeAssociation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaignCreativeAssociations.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + for &field in ["alt", "profileId", "campaignId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CampaignCreativeAssociation) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Campaign ID in this association. + pub fn campaign_id(mut self, new_value: &str) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignCreativeAssociationInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of creative IDs associated with the specified campaign. +/// +/// A builder for the *list* method supported by a *campaignCreativeAssociation* resource. +/// It is not used directly, but through a `CampaignCreativeAssociationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaign_creative_associations().list("profileId", "campaignId") +/// .sort_order("consetetur") +/// .page_token("sadipscing") +/// .max_results(-76) +/// .doit(); +/// # } +/// ``` +pub struct CampaignCreativeAssociationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _campaign_id: String, + _sort_order: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignCreativeAssociationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignCreativeAssociationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CampaignCreativeAssociationsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaignCreativeAssociations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("campaignId", self._campaign_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "profileId", "campaignId", "sortOrder", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{campaignId}", "campaignId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "campaignId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *campaign id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Campaign ID in this association. + pub fn campaign_id(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignCreativeAssociationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignCreativeAssociationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignCreativeAssociationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of change logs. +/// +/// A builder for the *list* method supported by a *changeLog* resource. +/// It is not used directly, but through a `ChangeLogMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.change_logs().list("profileId") +/// .add_user_profile_ids("invidunt") +/// .search_string("consetetur") +/// .page_token("dolore") +/// .object_type("duo") +/// .add_object_ids("aliquyam") +/// .min_change_time("Lorem") +/// .max_results(-17) +/// .max_change_time("clita") +/// .add_ids("consetetur") +/// .action("takimata") +/// .doit(); +/// # } +/// ``` +pub struct ChangeLogListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _user_profile_ids: Vec, + _search_string: Option, + _page_token: Option, + _object_type: Option, + _object_ids: Vec, + _min_change_time: Option, + _max_results: Option, + _max_change_time: Option, + _ids: Vec, + _action: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeLogListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeLogListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChangeLogsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.changeLogs.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._user_profile_ids.len() > 0 { + let mut s = String::new(); + for f in self._user_profile_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("userProfileIds", s)); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._object_type { + params.push(("objectType", value.to_string())); + } + if self._object_ids.len() > 0 { + let mut s = String::new(); + for f in self._object_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("objectIds", s)); + } + if let Some(value) = self._min_change_time { + params.push(("minChangeTime", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_change_time { + params.push(("maxChangeTime", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._action { + params.push(("action", value.to_string())); + } + for &field in ["alt", "profileId", "userProfileIds", "searchString", "pageToken", "objectType", "objectIds", "minChangeTime", "maxResults", "maxChangeTime", "ids", "action"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/changeLogs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *user profile ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only change logs with these user profile IDs. + pub fn add_user_profile_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._user_profile_ids.push(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Select only change logs whose object ID, user name, old or new values match the search string. + pub fn search_string(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *object type* query property to the given value. + /// + /// + /// Select only change logs with the specified object type. + pub fn object_type(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._object_type = Some(new_value.to_string()); + self + } + /// Append the given value to the *object ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only change logs with these object IDs. + pub fn add_object_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._object_ids.push(new_value.to_string()); + self + } + /// Sets the *min change time* query property to the given value. + /// + /// + /// Select only change logs whose change time is before the specified minChangeTime.The time should be formatted as an RFC3339 date/time string. For example, for 10:54 PM on July 18th, 2015, in the America/New York time zone, the format is "2015-07-18T22:54:00-04:00". In other words, the year, month, day, the letter T, the hour (24-hour clock system), minute, second, and then the time zone offset. + pub fn min_change_time(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._min_change_time = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> ChangeLogListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *max change time* query property to the given value. + /// + /// + /// Select only change logs whose change time is before the specified maxChangeTime.The time should be formatted as an RFC3339 date/time string. For example, for 10:54 PM on July 18th, 2015, in the America/New York time zone, the format is "2015-07-18T22:54:00-04:00". In other words, the year, month, day, the letter T, the hour (24-hour clock system), minute, second, and then the time zone offset. + pub fn max_change_time(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._max_change_time = Some(new_value.to_string()); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only change logs with these IDs. + pub fn add_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *action* query property to the given value. + /// + /// + /// Select only change logs with the specified action. + pub fn action(mut self, new_value: &str) -> ChangeLogListCall<'a, C, NC, A> { + self._action = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeLogListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeLogListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeLogListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one change log by ID. +/// +/// A builder for the *get* method supported by a *changeLog* resource. +/// It is not used directly, but through a `ChangeLogMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.change_logs().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ChangeLogGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeLogGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeLogGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChangeLog)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.changeLogs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/changeLogs/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ChangeLogGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Change log ID. + pub fn id(mut self, new_value: &str) -> ChangeLogGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeLogGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeLogGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeLogGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one account by ID. +/// +/// A builder for the *get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID. + pub fn id(mut self, new_value: &str) -> AccountGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of accounts, possibly filtered. +/// +/// A builder for the *list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().list("profileId") +/// .sort_order("labore") +/// .sort_field("invidunt") +/// .search_string("ea") +/// .page_token("sadipscing") +/// .max_results(-66) +/// .add_ids("dolore") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "account*2015" will return objects with names like "account June 2015", "account April 2015" or simply "account 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "account" will match objects with name "my account", "account 2015" or simply "account". + pub fn search_string(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> AccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only accounts with these IDs. + pub fn add_ids(mut self, new_value: &str) -> AccountListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *active* query property to the given value. + /// + /// + /// Select only active accounts. Don't set this field to select both active and non-active accounts. + pub fn active(mut self, new_value: bool) -> AccountListCall<'a, C, NC, A> { + self._active = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account. +/// +/// A builder for the *update* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AccountUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Account, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accounts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Account = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.accounts().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Account, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Account)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accounts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Account) -> AccountPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID. + pub fn id(mut self, new_value: &str) -> AccountPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of postal codes. +/// +/// A builder for the *list* method supported by a *postalCode* resource. +/// It is not used directly, but through a `PostalCodeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.postal_codes().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct PostalCodeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PostalCodeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PostalCodeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostalCodesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.postalCodes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/postalCodes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PostalCodeListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostalCodeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostalCodeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostalCodeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new advertiser. +/// +/// A builder for the *insert* method supported by a *advertiser* resource. +/// It is not used directly, but through a `AdvertiserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Advertiser = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertisers().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Advertiser, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Advertiser)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertisers.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Advertiser) -> AdvertiserInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing advertiser. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *advertiser* resource. +/// It is not used directly, but through a `AdvertiserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Advertiser = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertisers().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Advertiser, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Advertiser)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertisers.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Advertiser) -> AdvertiserPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser ID. + pub fn id(mut self, new_value: &str) -> AdvertiserPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of advertisers, possibly filtered. +/// +/// A builder for the *list* method supported by a *advertiser* resource. +/// It is not used directly, but through a `AdvertiserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertisers().list("profileId") +/// .subaccount_id("gubergren") +/// .status("aliquyam") +/// .sort_order("eos") +/// .sort_field("tempor") +/// .search_string("sea") +/// .page_token("labore") +/// .only_parent(false) +/// .max_results(-31) +/// .include_advertisers_without_groups_only(false) +/// .add_ids("sit") +/// .add_floodlight_configuration_ids("diam") +/// .add_advertiser_group_ids("ut") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _subaccount_id: Option, + _status: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _only_parent: Option, + _max_results: Option, + _include_advertisers_without_groups_only: Option, + _ids: Vec, + _floodlight_configuration_ids: Vec, + _advertiser_group_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertisersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertisers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((15 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._subaccount_id { + params.push(("subaccountId", value.to_string())); + } + if let Some(value) = self._status { + params.push(("status", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._only_parent { + params.push(("onlyParent", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_advertisers_without_groups_only { + params.push(("includeAdvertisersWithoutGroupsOnly", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._floodlight_configuration_ids.len() > 0 { + let mut s = String::new(); + for f in self._floodlight_configuration_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("floodlightConfigurationIds", s)); + } + if self._advertiser_group_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_group_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserGroupIds", s)); + } + for &field in ["alt", "profileId", "subaccountId", "status", "sortOrder", "sortField", "searchString", "pageToken", "onlyParent", "maxResults", "includeAdvertisersWithoutGroupsOnly", "ids", "floodlightConfigurationIds", "advertiserGroupIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *subaccount id* query property to the given value. + /// + /// + /// Select only advertisers with these subaccount IDs. + pub fn subaccount_id(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Sets the *status* query property to the given value. + /// + /// + /// Select only advertisers with the specified status. + pub fn status(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._status = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "advertiser*2015" will return objects with names like "advertiser June 2015", "advertiser April 2015" or simply "advertiser 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "advertiser" will match objects with name "my advertiser", "advertiser 2015" or simply "advertiser". + pub fn search_string(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *only parent* query property to the given value. + /// + /// + /// Select only advertisers which use another advertiser's floodlight configuration. + pub fn only_parent(mut self, new_value: bool) -> AdvertiserListCall<'a, C, NC, A> { + self._only_parent = Some(new_value); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> AdvertiserListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include advertisers without groups only* query property to the given value. + /// + /// + /// Select only advertisers which do not belong to any advertiser group. + pub fn include_advertisers_without_groups_only(mut self, new_value: bool) -> AdvertiserListCall<'a, C, NC, A> { + self._include_advertisers_without_groups_only = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only advertisers with these IDs. + pub fn add_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *floodlight configuration ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only advertisers with these floodlight configuration IDs. + pub fn add_floodlight_configuration_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._floodlight_configuration_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *advertiser group ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only advertisers with these advertiser group IDs. + pub fn add_advertiser_group_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, NC, A> { + self._advertiser_group_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing advertiser. +/// +/// A builder for the *update* method supported by a *advertiser* resource. +/// It is not used directly, but through a `AdvertiserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Advertiser = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertisers().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Advertiser, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Advertiser)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertisers.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Advertiser) -> AdvertiserUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one advertiser by ID. +/// +/// A builder for the *get* method supported by a *advertiser* resource. +/// It is not used directly, but through a `AdvertiserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertisers().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Advertiser)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertisers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertisers/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser ID. + pub fn id(mut self, new_value: &str) -> AdvertiserGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves list of report dimension values for a list of filters. +/// +/// A builder for the *query* method supported by a *dimensionValue* resource. +/// It is not used directly, but through a `DimensionValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::DimensionValueRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DimensionValueRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.dimension_values().query(&req, "profileId") +/// .page_token("clita") +/// .max_results(-79) +/// .doit(); +/// # } +/// ``` +pub struct DimensionValueQueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: DimensionValueRequest, + _profile_id: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DimensionValueQueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DimensionValueQueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DimensionValueList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.dimensionValues.query", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "profileId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/dimensionvalues/query".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DimensionValueRequest) -> DimensionValueQueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> DimensionValueQueryCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> DimensionValueQueryCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> DimensionValueQueryCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DimensionValueQueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DimensionValueQueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DimensionValueQueryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing floodlight activity group. +/// +/// A builder for the *delete* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity Group ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one floodlight activity group by ID. +/// +/// A builder for the *get* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivityGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity Group ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight activity group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivityGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivityGroup, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivityGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivityGroup) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity Group ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of floodlight activity groups, possibly filtered. +/// +/// A builder for the *list* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().list("profileId") +/// .type_("voluptua.") +/// .sort_order("duo") +/// .sort_field("sed") +/// .search_string("aliquyam") +/// .page_token("ea") +/// .max_results(-17) +/// .add_ids("et") +/// .floodlight_configuration_id("dolor") +/// .advertiser_id("diam") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _type_: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _floodlight_configuration_id: Option, + _advertiser_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivityGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._type_ { + params.push(("type", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._floodlight_configuration_id { + params.push(("floodlightConfigurationId", value.to_string())); + } + if let Some(value) = self._advertiser_id { + params.push(("advertiserId", value.to_string())); + } + for &field in ["alt", "profileId", "type", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "floodlightConfigurationId", "advertiserId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *type* query property to the given value. + /// + /// + /// Select only floodlight activity groups with the specified floodlight activity group type. + pub fn type_(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._type_ = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "floodlightactivitygroup*2015" will return objects with names like "floodlightactivitygroup June 2015", "floodlightactivitygroup April 2015" or simply "floodlightactivitygroup 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "floodlightactivitygroup" will match objects with name "my floodlightactivitygroup activity", "floodlightactivitygroup 2015" or simply "floodlightactivitygroup". + pub fn search_string(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only floodlight activity groups with the specified IDs. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn add_ids(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *floodlight configuration id* query property to the given value. + /// + /// + /// Select only floodlight activity groups with the specified floodlight configuration ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn floodlight_configuration_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._floodlight_configuration_id = Some(new_value.to_string()); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// + /// Select only floodlight activity groups with the specified advertiser ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn advertiser_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new floodlight activity group. +/// +/// A builder for the *insert* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivityGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivityGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivityGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivityGroup) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight activity group. +/// +/// A builder for the *update* method supported by a *floodlightActivityGroup* resource. +/// It is not used directly, but through a `FloodlightActivityGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivityGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activity_groups().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivityGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGroupUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGroupUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivityGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivityGroups.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivityGroup) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of metros. +/// +/// A builder for the *list* method supported by a *metro* resource. +/// It is not used directly, but through a `MetroMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.metros().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct MetroListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MetroListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MetroListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MetrosListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.metros.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/metros".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> MetroListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetroListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MetroListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MetroListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one directory site contact by ID. +/// +/// A builder for the *get* method supported by a *directorySiteContact* resource. +/// It is not used directly, but through a `DirectorySiteContactMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.directory_site_contacts().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteContactGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectorySiteContactGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteContactGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectorySiteContact)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.directorySiteContacts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/directorySiteContacts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteContactGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Directory site contact ID. + pub fn id(mut self, new_value: &str) -> DirectorySiteContactGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteContactGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectorySiteContactGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectorySiteContactGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of directory site contacts, possibly filtered. +/// +/// A builder for the *list* method supported by a *directorySiteContact* resource. +/// It is not used directly, but through a `DirectorySiteContactMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.directory_site_contacts().list("profileId") +/// .sort_order("eirmod") +/// .sort_field("At") +/// .search_string("consetetur") +/// .page_token("et") +/// .max_results(-80) +/// .add_ids("sit") +/// .add_directory_site_ids("takimata") +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteContactListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _directory_site_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectorySiteContactListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteContactListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectorySiteContactsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.directorySiteContacts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._directory_site_ids.len() > 0 { + let mut s = String::new(); + for f in self._directory_site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("directorySiteIds", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "directorySiteIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/directorySiteContacts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name, ID or email. Wildcards (*) are allowed. For example, "directory site contact*2015" will return objects with names like "directory site contact June 2015", "directory site contact April 2015" or simply "directory site contact 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "directory site contact" will match objects with name "my directory site contact", "directory site contact 2015" or simply "directory site contact". + pub fn search_string(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only directory site contacts with these IDs. + pub fn add_ids(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *directory site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only directory site contacts with these directory site IDs. This is a required field. + pub fn add_directory_site_ids(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteContactListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectorySiteContactListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectorySiteContactListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves list of user profiles for a user. +/// +/// A builder for the *list* method supported by a *userProfile* resource. +/// It is not used directly, but through a `UserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_profiles().list() +/// .doit(); +/// # } +/// ``` +pub struct UserProfileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserProfileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserProfileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserProfileList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userProfiles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserProfileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserProfileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserProfileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one user profile by ID. +/// +/// A builder for the *get* method supported by a *userProfile* resource. +/// It is not used directly, but through a `UserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_profiles().get("profileId") +/// .doit(); +/// # } +/// ``` +pub struct UserProfileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserProfileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserProfileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserProfile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userProfiles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The user profile ID. + pub fn profile_id(mut self, new_value: &str) -> UserProfileGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserProfileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserProfileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserProfileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing ad. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *ad* resource. +/// It is not used directly, but through a `AdMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Ad = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ads().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Ad, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Ad)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.ads.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Ad) -> AdPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad ID. + pub fn id(mut self, new_value: &str) -> AdPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new ad. +/// +/// A builder for the *insert* method supported by a *ad* resource. +/// It is not used directly, but through a `AdMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Ad = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ads().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Ad, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Ad)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.ads.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Ad) -> AdInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of ads, possibly filtered. +/// +/// A builder for the *list* method supported by a *ad* resource. +/// It is not used directly, but through a `AdMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ads().list("profileId") +/// .add_type("diam") +/// .ssl_required(true) +/// .ssl_compliant(true) +/// .sort_order("amet.") +/// .sort_field("ipsum") +/// .add_size_ids("ut") +/// .search_string("dolor") +/// .add_remarketing_list_ids("sea") +/// .add_placement_ids("ut") +/// .page_token("eirmod") +/// .overridden_event_tag_id("sanctus") +/// .max_results(-27) +/// .add_landing_page_ids("dolor") +/// .add_ids("et") +/// .dynamic_click_tracker(false) +/// .creative_type("vero") +/// .add_creative_optimization_configuration_ids("ut") +/// .add_creative_ids("sed") +/// .compatibility("et") +/// .add_campaign_ids("ipsum") +/// .add_audience_segment_ids("justo") +/// .archived(true) +/// .advertiser_id("vero") +/// .active(false) +/// .doit(); +/// # } +/// ``` +pub struct AdListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _type_: Vec, + _ssl_required: Option, + _ssl_compliant: Option, + _sort_order: Option, + _sort_field: Option, + _size_ids: Vec, + _search_string: Option, + _remarketing_list_ids: Vec, + _placement_ids: Vec, + _page_token: Option, + _overridden_event_tag_id: Option, + _max_results: Option, + _landing_page_ids: Vec, + _ids: Vec, + _dynamic_click_tracker: Option, + _creative_type: Option, + _creative_optimization_configuration_ids: Vec, + _creative_ids: Vec, + _compatibility: Option, + _campaign_ids: Vec, + _audience_segment_ids: Vec, + _archived: Option, + _advertiser_id: Option, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.ads.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((27 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._type_.len() > 0 { + let mut s = String::new(); + for f in self._type_.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("type", s)); + } + if let Some(value) = self._ssl_required { + params.push(("sslRequired", value.to_string())); + } + if let Some(value) = self._ssl_compliant { + params.push(("sslCompliant", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if self._size_ids.len() > 0 { + let mut s = String::new(); + for f in self._size_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sizeIds", s)); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if self._remarketing_list_ids.len() > 0 { + let mut s = String::new(); + for f in self._remarketing_list_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("remarketingListIds", s)); + } + if self._placement_ids.len() > 0 { + let mut s = String::new(); + for f in self._placement_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("placementIds", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._overridden_event_tag_id { + params.push(("overriddenEventTagId", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._landing_page_ids.len() > 0 { + let mut s = String::new(); + for f in self._landing_page_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("landingPageIds", s)); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._dynamic_click_tracker { + params.push(("dynamicClickTracker", value.to_string())); + } + if let Some(value) = self._creative_type { + params.push(("creativeType", value.to_string())); + } + if self._creative_optimization_configuration_ids.len() > 0 { + let mut s = String::new(); + for f in self._creative_optimization_configuration_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("creativeOptimizationConfigurationIds", s)); + } + if self._creative_ids.len() > 0 { + let mut s = String::new(); + for f in self._creative_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("creativeIds", s)); + } + if let Some(value) = self._compatibility { + params.push(("compatibility", value.to_string())); + } + if self._campaign_ids.len() > 0 { + let mut s = String::new(); + for f in self._campaign_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("campaignIds", s)); + } + if self._audience_segment_ids.len() > 0 { + let mut s = String::new(); + for f in self._audience_segment_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("audienceSegmentIds", s)); + } + if let Some(value) = self._archived { + params.push(("archived", value.to_string())); + } + if let Some(value) = self._advertiser_id { + params.push(("advertiserId", value.to_string())); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "type", "sslRequired", "sslCompliant", "sortOrder", "sortField", "sizeIds", "searchString", "remarketingListIds", "placementIds", "pageToken", "overriddenEventTagId", "maxResults", "landingPageIds", "ids", "dynamicClickTracker", "creativeType", "creativeOptimizationConfigurationIds", "creativeIds", "compatibility", "campaignIds", "audienceSegmentIds", "archived", "advertiserId", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *type* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these types. + pub fn add_type(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._type_.push(new_value.to_string()); + self + } + /// Sets the *ssl required* query property to the given value. + /// + /// + /// Select only ads that require SSL. + pub fn ssl_required(mut self, new_value: bool) -> AdListCall<'a, C, NC, A> { + self._ssl_required = Some(new_value); + self + } + /// Sets the *ssl compliant* query property to the given value. + /// + /// + /// Select only ads that are SSL-compliant. + pub fn ssl_compliant(mut self, new_value: bool) -> AdListCall<'a, C, NC, A> { + self._ssl_compliant = Some(new_value); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Append the given value to the *size ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these size IDs. + pub fn add_size_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "ad*2015" will return objects with names like "ad June 2015", "ad April 2015" or simply "ad 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "ad" will match objects with name "my ad", "ad 2015" or simply "ad". + pub fn search_string(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Append the given value to the *remarketing list ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads whose list targeting expression use these remarketing list IDs. + pub fn add_remarketing_list_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._remarketing_list_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *placement ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these placement IDs assigned. + pub fn add_placement_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._placement_ids.push(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *overridden event tag id* query property to the given value. + /// + /// + /// Select only ads with this event tag override ID. + pub fn overridden_event_tag_id(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._overridden_event_tag_id = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> AdListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *landing page ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these landing page IDs. + pub fn add_landing_page_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._landing_page_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these IDs. + pub fn add_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *dynamic click tracker* query property to the given value. + /// + /// + /// Select only dynamic click trackers. Applicable when type is AD_SERVING_CLICK_TRACKER. If true, select dynamic click trackers. If false, select static click trackers. Leave unset to select both. + pub fn dynamic_click_tracker(mut self, new_value: bool) -> AdListCall<'a, C, NC, A> { + self._dynamic_click_tracker = Some(new_value); + self + } + /// Sets the *creative type* query property to the given value. + /// + /// + /// Select only ads with the specified creativeType. + pub fn creative_type(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._creative_type = Some(new_value.to_string()); + self + } + /// Append the given value to the *creative optimization configuration ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these creative optimization configuration IDs. + pub fn add_creative_optimization_configuration_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._creative_optimization_configuration_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *creative ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these creative IDs assigned. + pub fn add_creative_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._creative_ids.push(new_value.to_string()); + self + } + /// Sets the *compatibility* query property to the given value. + /// + /// + /// Select default ads with the specified compatibility. Applicable when type is AD_SERVING_DEFAULT_AD. WEB and WEB_INTERSTITIAL refer to rendering either on desktop or on mobile devices for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are for rendering in mobile apps. IN_STREAM_VIDEO refers to rendering an in-stream video ads developed with the VAST standard. + pub fn compatibility(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._compatibility = Some(new_value.to_string()); + self + } + /// Append the given value to the *campaign ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these campaign IDs. + pub fn add_campaign_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *audience segment ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only ads with these audience segment IDs. + pub fn add_audience_segment_ids(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._audience_segment_ids.push(new_value.to_string()); + self + } + /// Sets the *archived* query property to the given value. + /// + /// + /// Select only archived ads. + pub fn archived(mut self, new_value: bool) -> AdListCall<'a, C, NC, A> { + self._archived = Some(new_value); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// + /// Select only ads with this advertiser ID. + pub fn advertiser_id(mut self, new_value: &str) -> AdListCall<'a, C, NC, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Sets the *active* query property to the given value. + /// + /// + /// Select only active ads. + pub fn active(mut self, new_value: bool) -> AdListCall<'a, C, NC, A> { + self._active = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one ad by ID. +/// +/// A builder for the *get* method supported by a *ad* resource. +/// It is not used directly, but through a `AdMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ads().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Ad)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.ads.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/ads/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Ad ID. + pub fn id(mut self, new_value: &str) -> AdGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing ad. +/// +/// A builder for the *update* method supported by a *ad* resource. +/// It is not used directly, but through a `AdMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Ad = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ads().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Ad, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Ad)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.ads.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Ad) -> AdUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one account permission by ID. +/// +/// A builder for the *get* method supported by a *accountPermission* resource. +/// It is not used directly, but through a `AccountPermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_permissions().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountPermissionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPermissionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountPermission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountPermissions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountPermissions/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account permission ID. + pub fn id(mut self, new_value: &str) -> AccountPermissionGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPermissionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPermissionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of account permissions. +/// +/// A builder for the *list* method supported by a *accountPermission* resource. +/// It is not used directly, but through a `AccountPermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_permissions().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPermissionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPermissionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountPermissionsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountPermissions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPermissionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPermissionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of connection types. +/// +/// A builder for the *list* method supported by a *connectionType* resource. +/// It is not used directly, but through a `ConnectionTypeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.connection_types().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct ConnectionTypeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConnectionTypeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConnectionTypeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConnectionTypesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.connectionTypes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/connectionTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ConnectionTypeListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConnectionTypeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConnectionTypeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConnectionTypeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one advertiser group by ID. +/// +/// A builder for the *get* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertiserGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser group ID. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of advertiser groups, possibly filtered. +/// +/// A builder for the *list* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().list("profileId") +/// .sort_order("elitr") +/// .sort_field("consetetur") +/// .search_string("sea") +/// .page_token("elitr") +/// .max_results(-77) +/// .add_ids("sea") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertiserGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "advertiser*2015" will return objects with names like "advertiser group June 2015", "advertiser group April 2015" or simply "advertiser group 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "advertisergroup" will match objects with name "my advertisergroup", "advertisergroup 2015" or simply "advertisergroup". + pub fn search_string(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only advertiser groups with these IDs. + pub fn add_ids(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new advertiser group. +/// +/// A builder for the *insert* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdvertiserGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AdvertiserGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertiserGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdvertiserGroup) -> AdvertiserGroupInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing advertiser group. +/// +/// A builder for the *update* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdvertiserGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AdvertiserGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertiserGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdvertiserGroup) -> AdvertiserGroupUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing advertiser group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AdvertiserGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AdvertiserGroup, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AdvertiserGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AdvertiserGroup) -> AdvertiserGroupPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser group ID. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing advertiser group. +/// +/// A builder for the *delete* method supported by a *advertiserGroup* resource. +/// It is not used directly, but through a `AdvertiserGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.advertiser_groups().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AdvertiserGroupDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AdvertiserGroupDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.advertiserGroups.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/advertiserGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser group ID. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AdvertiserGroupDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AdvertiserGroupDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new site. +/// +/// A builder for the *insert* method supported by a *site* resource. +/// It is not used directly, but through a `SiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Site = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sites().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct SiteInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Site, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SiteInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SiteInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Site)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sites.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Site) -> SiteInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SiteInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SiteInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SiteInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one site by ID. +/// +/// A builder for the *get* method supported by a *site* resource. +/// It is not used directly, but through a `SiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sites().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct SiteGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SiteGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SiteGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Site)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sites.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sites/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SiteGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Site ID. + pub fn id(mut self, new_value: &str) -> SiteGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SiteGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SiteGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of sites, possibly filtered. +/// +/// A builder for the *list* method supported by a *site* resource. +/// It is not used directly, but through a `SiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sites().list("profileId") +/// .unmapped_site(false) +/// .subaccount_id("sed") +/// .sort_order("dolor") +/// .sort_field("sanctus") +/// .search_string("dolore") +/// .page_token("Lorem") +/// .max_results(-96) +/// .add_ids("consetetur") +/// .add_directory_site_ids("eirmod") +/// .add_campaign_ids("labore") +/// .approved(false) +/// .ad_words_site(false) +/// .accepts_publisher_paid_placements(true) +/// .accepts_interstitial_placements(false) +/// .accepts_in_stream_video_placements(true) +/// .doit(); +/// # } +/// ``` +pub struct SiteListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _unmapped_site: Option, + _subaccount_id: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _directory_site_ids: Vec, + _campaign_ids: Vec, + _approved: Option, + _ad_words_site: Option, + _accepts_publisher_paid_placements: Option, + _accepts_interstitial_placements: Option, + _accepts_in_stream_video_placements: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SiteListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SiteListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SitesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sites.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((18 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._unmapped_site { + params.push(("unmappedSite", value.to_string())); + } + if let Some(value) = self._subaccount_id { + params.push(("subaccountId", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._directory_site_ids.len() > 0 { + let mut s = String::new(); + for f in self._directory_site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("directorySiteIds", s)); + } + if self._campaign_ids.len() > 0 { + let mut s = String::new(); + for f in self._campaign_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("campaignIds", s)); + } + if let Some(value) = self._approved { + params.push(("approved", value.to_string())); + } + if let Some(value) = self._ad_words_site { + params.push(("adWordsSite", value.to_string())); + } + if let Some(value) = self._accepts_publisher_paid_placements { + params.push(("acceptsPublisherPaidPlacements", value.to_string())); + } + if let Some(value) = self._accepts_interstitial_placements { + params.push(("acceptsInterstitialPlacements", value.to_string())); + } + if let Some(value) = self._accepts_in_stream_video_placements { + params.push(("acceptsInStreamVideoPlacements", value.to_string())); + } + for &field in ["alt", "profileId", "unmappedSite", "subaccountId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "directorySiteIds", "campaignIds", "approved", "adWordsSite", "acceptsPublisherPaidPlacements", "acceptsInterstitialPlacements", "acceptsInStreamVideoPlacements"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *unmapped site* query property to the given value. + /// + /// + /// Select only sites that have not been mapped to a directory site. + pub fn unmapped_site(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._unmapped_site = Some(new_value); + self + } + /// Sets the *subaccount id* query property to the given value. + /// + /// + /// Select only sites with this subaccount ID. + pub fn subaccount_id(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name, ID or keyName. Wildcards (*) are allowed. For example, "site*2015" will return objects with names like "site June 2015", "site April 2015" or simply "site 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "site" will match objects with name "my site", "site 2015" or simply "site". + pub fn search_string(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> SiteListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only sites with these IDs. + pub fn add_ids(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *directory site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only sites with these directory site IDs. + pub fn add_directory_site_ids(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *campaign ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only sites with these campaign IDs. + pub fn add_campaign_ids(mut self, new_value: &str) -> SiteListCall<'a, C, NC, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Sets the *approved* query property to the given value. + /// + /// + /// Select only approved sites. + pub fn approved(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._approved = Some(new_value); + self + } + /// Sets the *ad words site* query property to the given value. + /// + /// + /// Select only AdWords sites. + pub fn ad_words_site(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._ad_words_site = Some(new_value); + self + } + /// Sets the *accepts publisher paid placements* query property to the given value. + /// + /// + /// Select only sites that accept publisher paid placements. + pub fn accepts_publisher_paid_placements(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._accepts_publisher_paid_placements = Some(new_value); + self + } + /// Sets the *accepts interstitial placements* query property to the given value. + /// + /// + /// This search filter is no longer supported and will have no effect on the results returned. + pub fn accepts_interstitial_placements(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._accepts_interstitial_placements = Some(new_value); + self + } + /// Sets the *accepts in stream video placements* query property to the given value. + /// + /// + /// This search filter is no longer supported and will have no effect on the results returned. + pub fn accepts_in_stream_video_placements(mut self, new_value: bool) -> SiteListCall<'a, C, NC, A> { + self._accepts_in_stream_video_placements = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SiteListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SiteListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing site. +/// +/// A builder for the *update* method supported by a *site* resource. +/// It is not used directly, but through a `SiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Site = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sites().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct SiteUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Site, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SiteUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SiteUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Site)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sites.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Site) -> SiteUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SiteUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SiteUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SiteUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing site. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *site* resource. +/// It is not used directly, but through a `SiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Site = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sites().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct SitePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Site, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SitePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SitePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Site)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sites.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Site) -> SitePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SitePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Site ID. + pub fn id(mut self, new_value: &str) -> SitePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SitePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SitePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SitePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one floodlight activity by ID. +/// +/// A builder for the *get* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivity)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of floodlight activities, possibly filtered. +/// +/// A builder for the *list* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().list("profileId") +/// .tag_string("vero") +/// .sort_order("consetetur") +/// .sort_field("vero") +/// .search_string("consetetur") +/// .page_token("eos") +/// .max_results(-21) +/// .add_ids("tempor") +/// .floodlight_configuration_id("gubergren") +/// .floodlight_activity_group_type("dolore") +/// .floodlight_activity_group_tag_string("amet.") +/// .floodlight_activity_group_name("dolore") +/// .add_floodlight_activity_group_ids("magna") +/// .advertiser_id("elitr") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _tag_string: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _floodlight_configuration_id: Option, + _floodlight_activity_group_type: Option, + _floodlight_activity_group_tag_string: Option, + _floodlight_activity_group_name: Option, + _floodlight_activity_group_ids: Vec, + _advertiser_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivitiesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((16 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._tag_string { + params.push(("tagString", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._floodlight_configuration_id { + params.push(("floodlightConfigurationId", value.to_string())); + } + if let Some(value) = self._floodlight_activity_group_type { + params.push(("floodlightActivityGroupType", value.to_string())); + } + if let Some(value) = self._floodlight_activity_group_tag_string { + params.push(("floodlightActivityGroupTagString", value.to_string())); + } + if let Some(value) = self._floodlight_activity_group_name { + params.push(("floodlightActivityGroupName", value.to_string())); + } + if self._floodlight_activity_group_ids.len() > 0 { + let mut s = String::new(); + for f in self._floodlight_activity_group_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("floodlightActivityGroupIds", s)); + } + if let Some(value) = self._advertiser_id { + params.push(("advertiserId", value.to_string())); + } + for &field in ["alt", "profileId", "tagString", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "floodlightConfigurationId", "floodlightActivityGroupType", "floodlightActivityGroupTagString", "floodlightActivityGroupName", "floodlightActivityGroupIds", "advertiserId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *tag string* query property to the given value. + /// + /// + /// Select only floodlight activities with the specified tag string. + pub fn tag_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._tag_string = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "floodlightactivity*2015" will return objects with names like "floodlightactivity June 2015", "floodlightactivity April 2015" or simply "floodlightactivity 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "floodlightactivity" will match objects with name "my floodlightactivity activity", "floodlightactivity 2015" or simply "floodlightactivity". + pub fn search_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> FloodlightActivityListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only floodlight activities with the specified IDs. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn add_ids(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *floodlight configuration id* query property to the given value. + /// + /// + /// Select only floodlight activities for the specified floodlight configuration ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn floodlight_configuration_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._floodlight_configuration_id = Some(new_value.to_string()); + self + } + /// Sets the *floodlight activity group type* query property to the given value. + /// + /// + /// Select only floodlight activities with the specified floodlight activity group type. + pub fn floodlight_activity_group_type(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._floodlight_activity_group_type = Some(new_value.to_string()); + self + } + /// Sets the *floodlight activity group tag string* query property to the given value. + /// + /// + /// Select only floodlight activities with the specified floodlight activity group tag string. + pub fn floodlight_activity_group_tag_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._floodlight_activity_group_tag_string = Some(new_value.to_string()); + self + } + /// Sets the *floodlight activity group name* query property to the given value. + /// + /// + /// Select only floodlight activities with the specified floodlight activity group name. + pub fn floodlight_activity_group_name(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._floodlight_activity_group_name = Some(new_value.to_string()); + self + } + /// Append the given value to the *floodlight activity group ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only floodlight activities with the specified floodlight activity group IDs. + pub fn add_floodlight_activity_group_ids(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._floodlight_activity_group_ids.push(new_value.to_string()); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// + /// Select only floodlight activities for the specified advertiser ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + pub fn advertiser_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, NC, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new floodlight activity. +/// +/// A builder for the *insert* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivity = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivity, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivity)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivity) -> FloodlightActivityInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing floodlight activity. +/// +/// A builder for the *delete* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight activity. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivity = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivity, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivity)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivity) -> FloodlightActivityPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight activity ID. + pub fn id(mut self, new_value: &str) -> FloodlightActivityPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generates a tag for a floodlight activity. +/// +/// A builder for the *generatetag* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().generatetag("profileId") +/// .floodlight_activity_id("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGeneratetagCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _floodlight_activity_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityGeneratetagCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityGeneratetagCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivitiesGenerateTagResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.generatetag", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._floodlight_activity_id { + params.push(("floodlightActivityId", value.to_string())); + } + for &field in ["alt", "profileId", "floodlightActivityId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities/generatetag".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *floodlight activity id* query property to the given value. + /// + /// + /// Floodlight activity ID for which we want to generate a tag. + pub fn floodlight_activity_id(mut self, new_value: &str) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> { + self._floodlight_activity_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityGeneratetagCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight activity. +/// +/// A builder for the *update* method supported by a *floodlightActivity* resource. +/// It is not used directly, but through a `FloodlightActivityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightActivity = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_activities().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivity, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightActivityUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightActivityUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightActivity)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightActivities.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightActivity) -> FloodlightActivityUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightActivityUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightActivityUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of regions. +/// +/// A builder for the *list* method supported by a *region* resource. +/// It is not used directly, but through a `RegionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.regions().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct RegionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RegionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RegionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RegionsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.regions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/regions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> RegionListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RegionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RegionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new creative group. +/// +/// A builder for the *insert* method supported by a *creativeGroup* resource. +/// It is not used directly, but through a `CreativeGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_groups().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGroupInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeGroups.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeGroup) -> CreativeGroupInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGroupInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGroupInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one creative group by ID. +/// +/// A builder for the *get* method supported by a *creativeGroup* resource. +/// It is not used directly, but through a `CreativeGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative group ID. + pub fn id(mut self, new_value: &str) -> CreativeGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative group. +/// +/// A builder for the *update* method supported by a *creativeGroup* resource. +/// It is not used directly, but through a `CreativeGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_groups().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGroupUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeGroups.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeGroup) -> CreativeGroupUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of creative groups, possibly filtered. +/// +/// A builder for the *list* method supported by a *creativeGroup* resource. +/// It is not used directly, but through a `CreativeGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_groups().list("profileId") +/// .sort_order("nonumy") +/// .sort_field("takimata") +/// .search_string("dolores") +/// .page_token("consetetur") +/// .max_results(-30) +/// .add_ids("amet.") +/// .group_number(-18) +/// .add_advertiser_ids("dolores") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _group_number: Option, + _advertiser_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._group_number { + params.push(("groupNumber", value.to_string())); + } + if self._advertiser_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserIds", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "groupNumber", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for creative groups by name or ID. Wildcards (*) are allowed. For example, "creativegroup*2015" will return creative groups with names like "creativegroup June 2015", "creativegroup April 2015" or simply "creativegroup 2015". Most of the searches also add wild-cards implicitly at the start and the end of the search string. For example, a search string of "creativegroup" will match creative groups with the name "my creativegroup", "creativegroup 2015" or simply "creativegroup". + pub fn search_string(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CreativeGroupListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creative groups with these IDs. + pub fn add_ids(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *group number* query property to the given value. + /// + /// + /// Select only creative groups that belong to this subgroup. + pub fn group_number(mut self, new_value: i32) -> CreativeGroupListCall<'a, C, NC, A> { + self._group_number = Some(new_value); + self + } + /// Append the given value to the *advertiser ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creative groups that belong to these advertisers. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, NC, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *creativeGroup* resource. +/// It is not used directly, but through a `CreativeGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_groups().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeGroup, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGroupPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGroupPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeGroups.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeGroup) -> CreativeGroupPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative group ID. + pub fn id(mut self, new_value: &str) -> CreativeGroupPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGroupPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGroupPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing subaccount. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *subaccount* resource. +/// It is not used directly, but through a `SubaccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Subaccount = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.subaccounts().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Subaccount, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SubaccountPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subaccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.subaccounts.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Subaccount) -> SubaccountPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SubaccountPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Subaccount ID. + pub fn id(mut self, new_value: &str) -> SubaccountPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SubaccountPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SubaccountPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new subaccount. +/// +/// A builder for the *insert* method supported by a *subaccount* resource. +/// It is not used directly, but through a `SubaccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Subaccount = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.subaccounts().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Subaccount, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SubaccountInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subaccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.subaccounts.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Subaccount) -> SubaccountInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SubaccountInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SubaccountInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SubaccountInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a list of subaccounts, possibly filtered. +/// +/// A builder for the *list* method supported by a *subaccount* resource. +/// It is not used directly, but through a `SubaccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.subaccounts().list("profileId") +/// .sort_order("aliquyam") +/// .sort_field("sadipscing") +/// .search_string("magna") +/// .page_token("gubergren") +/// .max_results(-98) +/// .add_ids("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SubaccountListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SubaccountsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.subaccounts.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "subaccount*2015" will return objects with names like "subaccount June 2015", "subaccount April 2015" or simply "subaccount 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "subaccount" will match objects with name "my subaccount", "subaccount 2015" or simply "subaccount". + pub fn search_string(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> SubaccountListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only subaccounts with these IDs. + pub fn add_ids(mut self, new_value: &str) -> SubaccountListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SubaccountListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SubaccountListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing subaccount. +/// +/// A builder for the *update* method supported by a *subaccount* resource. +/// It is not used directly, but through a `SubaccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Subaccount = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.subaccounts().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Subaccount, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SubaccountUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subaccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.subaccounts.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Subaccount) -> SubaccountUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SubaccountUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SubaccountUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SubaccountUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one subaccount by ID. +/// +/// A builder for the *get* method supported by a *subaccount* resource. +/// It is not used directly, but through a `SubaccountMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.subaccounts().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SubaccountGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SubaccountGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subaccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.subaccounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/subaccounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SubaccountGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Subaccount ID. + pub fn id(mut self, new_value: &str) -> SubaccountGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SubaccountGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SubaccountGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of mobile carriers. +/// +/// A builder for the *list* method supported by a *mobileCarrier* resource. +/// It is not used directly, but through a `MobileCarrierMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.mobile_carriers().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct MobileCarrierListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for MobileCarrierListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MobileCarrierListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MobileCarriersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.mobileCarriers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/mobileCarriers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> MobileCarrierListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobileCarrierListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobileCarrierListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobileCarrierListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight configuration. +/// +/// A builder for the *update* method supported by a *floodlightConfiguration* resource. +/// It is not used directly, but through a `FloodlightConfigurationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightConfiguration; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightConfiguration = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_configurations().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightConfigurationUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightConfiguration, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightConfigurationUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightConfigurationUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightConfiguration)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightConfigurations.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightConfiguration) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightConfigurationUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing floodlight configuration. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *floodlightConfiguration* resource. +/// It is not used directly, but through a `FloodlightConfigurationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::FloodlightConfiguration; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: FloodlightConfiguration = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_configurations().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightConfigurationPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightConfiguration, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightConfigurationPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightConfigurationPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightConfiguration)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightConfigurations.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &FloodlightConfiguration) -> FloodlightConfigurationPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight configuration ID. + pub fn id(mut self, new_value: &str) -> FloodlightConfigurationPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightConfigurationPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightConfigurationPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one floodlight configuration by ID. +/// +/// A builder for the *get* method supported by a *floodlightConfiguration* resource. +/// It is not used directly, but through a `FloodlightConfigurationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_configurations().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightConfigurationGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightConfigurationGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightConfigurationGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightConfiguration)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightConfigurations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightConfigurations/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Floodlight configuration ID. + pub fn id(mut self, new_value: &str) -> FloodlightConfigurationGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightConfigurationGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightConfigurationGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of floodlight configurations, possibly filtered. +/// +/// A builder for the *list* method supported by a *floodlightConfiguration* resource. +/// It is not used directly, but through a `FloodlightConfigurationMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.floodlight_configurations().list("profileId") +/// .add_ids("sed") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightConfigurationListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FloodlightConfigurationListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FloodlightConfigurationListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FloodlightConfigurationsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.floodlightConfigurations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Set of IDs of floodlight configurations to retrieve. Required field; otherwise an empty list will be returned. + pub fn add_ids(mut self, new_value: &str) -> FloodlightConfigurationListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FloodlightConfigurationListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FloodlightConfigurationListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of operating systems. +/// +/// A builder for the *list* method supported by a *operatingSystem* resource. +/// It is not used directly, but through a `OperatingSystemMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.operating_systems().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct OperatingSystemListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for OperatingSystemListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> OperatingSystemListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperatingSystemsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.operatingSystems.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/operatingSystems".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperatingSystemListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperatingSystemListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists files for a user profile. +/// +/// A builder for the *list* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().list("profileId") +/// .sort_order("et") +/// .sort_field("At") +/// .scope("sit") +/// .page_token("ut") +/// .max_results(-78) +/// .doit(); +/// # } +/// ``` +pub struct FileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _scope: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FileList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.files.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._scope { + params.push(("scope", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "scope", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/files".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA profile ID. + pub fn profile_id(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is 'DESCENDING'. + pub fn sort_order(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// The field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *scope* query property to the given value. + /// + /// + /// The scope that defines which results are returned, default is 'MINE'. + pub fn scope(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._scope = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> FileListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a report file by its report ID and file ID. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `File` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *get* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().get("reportId", "fileId") +/// .doit(); +/// # } +/// ``` +pub struct FileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _report_id: String, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.files.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("reportId", self._report_id.to_string())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["reportId", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/reports/{reportId}/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{reportId}", "reportId"), ("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["reportId", "fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> FileGetCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report file. + pub fn file_id(mut self, new_value: &str) -> FileGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of placement groups, possibly filtered. +/// +/// A builder for the *list* method supported by a *placementGroup* resource. +/// It is not used directly, but through a `PlacementGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_groups().list("profileId") +/// .sort_order("dolores") +/// .sort_field("kasd") +/// .add_site_ids("et") +/// .search_string("clita") +/// .add_pricing_types("sed") +/// .add_placement_strategy_ids("dolores") +/// .placement_group_type("clita") +/// .page_token("eos") +/// .max_results(-47) +/// .add_ids("sed") +/// .add_directory_site_ids("takimata") +/// .add_content_category_ids("sit") +/// .add_campaign_ids("labore") +/// .archived(false) +/// .add_advertiser_ids("erat") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _site_ids: Vec, + _search_string: Option, + _pricing_types: Vec, + _placement_strategy_ids: Vec, + _placement_group_type: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _directory_site_ids: Vec, + _content_category_ids: Vec, + _campaign_ids: Vec, + _archived: Option, + _advertiser_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((18 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if self._site_ids.len() > 0 { + let mut s = String::new(); + for f in self._site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("siteIds", s)); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if self._pricing_types.len() > 0 { + let mut s = String::new(); + for f in self._pricing_types.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pricingTypes", s)); + } + if self._placement_strategy_ids.len() > 0 { + let mut s = String::new(); + for f in self._placement_strategy_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("placementStrategyIds", s)); + } + if let Some(value) = self._placement_group_type { + params.push(("placementGroupType", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._directory_site_ids.len() > 0 { + let mut s = String::new(); + for f in self._directory_site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("directorySiteIds", s)); + } + if self._content_category_ids.len() > 0 { + let mut s = String::new(); + for f in self._content_category_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("contentCategoryIds", s)); + } + if self._campaign_ids.len() > 0 { + let mut s = String::new(); + for f in self._campaign_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("campaignIds", s)); + } + if let Some(value) = self._archived { + params.push(("archived", value.to_string())); + } + if self._advertiser_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserIds", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "siteIds", "searchString", "pricingTypes", "placementStrategyIds", "placementGroupType", "pageToken", "maxResults", "ids", "directorySiteIds", "contentCategoryIds", "campaignIds", "archived", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Append the given value to the *site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that are associated with these sites. + pub fn add_site_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._site_ids.push(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for placement groups by name or ID. Wildcards (*) are allowed. For example, "placement*2015" will return placement groups with names like "placement group June 2015", "placement group May 2015" or simply "placements 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "placementgroup" will match placement groups with name "my placementgroup", "placementgroup 2015" or simply "placementgroup". + pub fn search_string(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Append the given value to the *pricing types* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups with these pricing types. + pub fn add_pricing_types(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._pricing_types.push(new_value.to_string()); + self + } + /// Append the given value to the *placement strategy ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that are associated with these placement strategies. + pub fn add_placement_strategy_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._placement_strategy_ids.push(new_value.to_string()); + self + } + /// Sets the *placement group type* query property to the given value. + /// + /// + /// Select only placement groups belonging with this group type. A package is a simple group of placements that acts as a single pricing point for a group of tags. A roadblock is a group of placements that not only acts as a single pricing point but also assumes that all the tags in it will be served at the same time. A roadblock requires one of its assigned placements to be marked as primary for reporting. + pub fn placement_group_type(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._placement_group_type = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> PlacementGroupListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups with these IDs. + pub fn add_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *directory site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that are associated with these directory sites. + pub fn add_directory_site_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *content category ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that are associated with these content categories. + pub fn add_content_category_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._content_category_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *campaign ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that belong to these campaigns. + pub fn add_campaign_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Sets the *archived* query property to the given value. + /// + /// + /// Select only archived placements. Don't set this field to select both archived and non-archived placements. + pub fn archived(mut self, new_value: bool) -> PlacementGroupListCall<'a, C, NC, A> { + self._archived = Some(new_value); + self + } + /// Append the given value to the *advertiser ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement groups that belong to these advertisers. + pub fn add_advertiser_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, NC, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement group. +/// +/// A builder for the *update* method supported by a *placementGroup* resource. +/// It is not used directly, but through a `PlacementGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_groups().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGroupUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementGroups.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementGroup) -> PlacementGroupUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGroupUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new placement group. +/// +/// A builder for the *insert* method supported by a *placementGroup* resource. +/// It is not used directly, but through a `PlacementGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_groups().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGroupInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementGroups.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementGroup) -> PlacementGroupInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGroupInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGroupInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one placement group by ID. +/// +/// A builder for the *get* method supported by a *placementGroup* resource. +/// It is not used directly, but through a `PlacementGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement group ID. + pub fn id(mut self, new_value: &str) -> PlacementGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement group. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *placementGroup* resource. +/// It is not used directly, but through a `PlacementGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementGroup = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_groups().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementGroup, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGroupPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGroupPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementGroups.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementGroup) -> PlacementGroupPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement group ID. + pub fn id(mut self, new_value: &str) -> PlacementGroupPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGroupPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGroupPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new creative asset. +/// +/// A builder for the *insert* method supported by a *creativeAsset* resource. +/// It is not used directly, but through a `CreativeAssetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeAssetMetadata; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeAssetMetadata = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_assets().insert(&req, "profileId", "advertiserId") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct CreativeAssetInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeAssetMetadata, + _profile_id: String, + _advertiser_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeAssetInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeAssetInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, CreativeAssetMetadata)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeAssets.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("advertiserId", self._advertiser_id.to_string())); + for &field in ["alt", "profileId", "advertiserId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/dfareporting/v2.0/userprofiles/{profileId}/creativeAssets/{advertiserId}/creativeAssets".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/dfareporting/v2.0/userprofiles/{profileId}/creativeAssets/{advertiserId}/creativeAssets".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{advertiserId}", "advertiserId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "advertiserId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut mp_reader: MultiPartReader = Default::default(); + let (mut body_reader, content_type) = match protocol { + "simple" => { + mp_reader.reserve_exact(2); + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone()) + .add_part(&mut reader, size, reader_mime_type.clone()); + let mime_type = mp_reader.mime_type(); + (&mut mp_reader as &mut io::Read, ContentType(mime_type)) + }, + _ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())), + }; + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(content_type) + .body(&mut body_reader); + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 100MB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, CreativeAssetMetadata)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 100MB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, CreativeAssetMetadata)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeAssetMetadata) -> CreativeAssetInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeAssetInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *advertiser id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Advertiser ID of this creative. This is a required field. + pub fn advertiser_id(mut self, new_value: &str) -> CreativeAssetInsertCall<'a, C, NC, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeAssetInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeAssetInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeAssetInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one user role permission by ID. +/// +/// A builder for the *get* method supported by a *userRolePermission* resource. +/// It is not used directly, but through a `UserRolePermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_role_permissions().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePermissionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRolePermissionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRolePermission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRolePermissions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRolePermissions/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User role permission ID. + pub fn id(mut self, new_value: &str) -> UserRolePermissionGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRolePermissionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRolePermissionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a list of user role permissions, possibly filtered. +/// +/// A builder for the *list* method supported by a *userRolePermission* resource. +/// It is not used directly, but through a `UserRolePermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.user_role_permissions().list("profileId") +/// .add_ids("dolor") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePermissionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserRolePermissionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserRolePermissionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserRolePermissionsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.userRolePermissions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/userRolePermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only user role permissions with these IDs. + pub fn add_ids(mut self, new_value: &str) -> UserRolePermissionListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRolePermissionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRolePermissionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves the list of account permission groups. +/// +/// A builder for the *list* method supported by a *accountPermissionGroup* resource. +/// It is not used directly, but through a `AccountPermissionGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_permission_groups().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct AccountPermissionGroupListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPermissionGroupListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionGroupListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountPermissionGroupsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountPermissionGroups.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountPermissionGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGroupListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGroupListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPermissionGroupListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPermissionGroupListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one account permission group by ID. +/// +/// A builder for the *get* method supported by a *accountPermissionGroup* resource. +/// It is not used directly, but through a `AccountPermissionGroupMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_permission_groups().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountPermissionGroupGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountPermissionGroupGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountPermissionGroupGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountPermissionGroup)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountPermissionGroups.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountPermissionGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGroupGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account permission group ID. + pub fn id(mut self, new_value: &str) -> AccountPermissionGroupGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGroupGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountPermissionGroupGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountPermissionGroupGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of content categories, possibly filtered. +/// +/// A builder for the *list* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().list("profileId") +/// .sort_order("magna") +/// .sort_field("et") +/// .search_string("sed") +/// .page_token("est") +/// .max_results(-48) +/// .add_ids("et") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ContentCategoriesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "contentcategory*2015" will return objects with names like "contentcategory June 2015", "contentcategory April 2015" or simply "contentcategory 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "contentcategory" will match objects with name "my contentcategory", "contentcategory 2015" or simply "contentcategory". + pub fn search_string(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> ContentCategoryListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only content categories with these IDs. + pub fn add_ids(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing content category. +/// +/// A builder for the *update* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ContentCategory = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: ContentCategory, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ContentCategory)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ContentCategory) -> ContentCategoryUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new content category. +/// +/// A builder for the *insert* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ContentCategory = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: ContentCategory, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ContentCategory)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ContentCategory) -> ContentCategoryInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing content category. +/// +/// A builder for the *delete* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Content category ID. + pub fn id(mut self, new_value: &str) -> ContentCategoryDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one content category by ID. +/// +/// A builder for the *get* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ContentCategory)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Content category ID. + pub fn id(mut self, new_value: &str) -> ContentCategoryGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing content category. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *contentCategory* resource. +/// It is not used directly, but through a `ContentCategoryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ContentCategory = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.content_categories().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: ContentCategory, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ContentCategoryPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ContentCategoryPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ContentCategory)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.contentCategories.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ContentCategory) -> ContentCategoryPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Content category ID. + pub fn id(mut self, new_value: &str) -> ContentCategoryPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ContentCategoryPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ContentCategoryPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new creative. +/// +/// A builder for the *insert* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Creative = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Creative, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creatives.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Creative) -> CreativeInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative. +/// +/// A builder for the *update* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Creative = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Creative, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creatives.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Creative) -> CreativeUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one creative by ID. +/// +/// A builder for the *get* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creatives.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creatives/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative ID. + pub fn id(mut self, new_value: &str) -> CreativeGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of creatives, possibly filtered. +/// +/// A builder for the *list* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().list("profileId") +/// .add_types("sit") +/// .studio_creative_id("sit") +/// .sort_order("dolores") +/// .sort_field("et") +/// .add_size_ids("sanctus") +/// .search_string("takimata") +/// .add_rendering_ids("kasd") +/// .page_token("ut") +/// .max_results(-44) +/// .add_ids("et") +/// .add_creative_field_ids("clita") +/// .add_companion_creative_ids("ipsum") +/// .campaign_id("dolor") +/// .archived(false) +/// .advertiser_id("magna") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct CreativeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _types: Vec, + _studio_creative_id: Option, + _sort_order: Option, + _sort_field: Option, + _size_ids: Vec, + _search_string: Option, + _rendering_ids: Vec, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _creative_field_ids: Vec, + _companion_creative_ids: Vec, + _campaign_id: Option, + _archived: Option, + _advertiser_id: Option, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creatives.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((19 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._types.len() > 0 { + let mut s = String::new(); + for f in self._types.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("types", s)); + } + if let Some(value) = self._studio_creative_id { + params.push(("studioCreativeId", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if self._size_ids.len() > 0 { + let mut s = String::new(); + for f in self._size_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sizeIds", s)); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if self._rendering_ids.len() > 0 { + let mut s = String::new(); + for f in self._rendering_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("renderingIds", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._creative_field_ids.len() > 0 { + let mut s = String::new(); + for f in self._creative_field_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("creativeFieldIds", s)); + } + if self._companion_creative_ids.len() > 0 { + let mut s = String::new(); + for f in self._companion_creative_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("companionCreativeIds", s)); + } + if let Some(value) = self._campaign_id { + params.push(("campaignId", value.to_string())); + } + if let Some(value) = self._archived { + params.push(("archived", value.to_string())); + } + if let Some(value) = self._advertiser_id { + params.push(("advertiserId", value.to_string())); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "types", "studioCreativeId", "sortOrder", "sortField", "sizeIds", "searchString", "renderingIds", "pageToken", "maxResults", "ids", "creativeFieldIds", "companionCreativeIds", "campaignId", "archived", "advertiserId", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *types* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creatives with these creative types. + pub fn add_types(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._types.push(new_value.to_string()); + self + } + /// Sets the *studio creative id* query property to the given value. + /// + /// + /// Select only creatives corresponding to this Studio creative ID. + pub fn studio_creative_id(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._studio_creative_id = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Append the given value to the *size ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creatives with these size IDs. + pub fn add_size_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "creative*2015" will return objects with names like "creative June 2015", "creative April 2015" or simply "creative 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "creative" will match objects with name "my creative", "creative 2015" or simply "creative". + pub fn search_string(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Append the given value to the *rendering ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creatives with these rendering IDs. + pub fn add_rendering_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._rendering_ids.push(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CreativeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creatives with these IDs. + pub fn add_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *creative field ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creatives with these creative field IDs. + pub fn add_creative_field_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._creative_field_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *companion creative ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only in-stream video creatives with these companion IDs. + pub fn add_companion_creative_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._companion_creative_ids.push(new_value.to_string()); + self + } + /// Sets the *campaign id* query property to the given value. + /// + /// + /// Select only creatives with this campaign ID. + pub fn campaign_id(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Sets the *archived* query property to the given value. + /// + /// + /// Select only archived creatives. Leave blank to select archived and unarchived creatives. + pub fn archived(mut self, new_value: bool) -> CreativeListCall<'a, C, NC, A> { + self._archived = Some(new_value); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// + /// Select only creatives with this advertiser ID. + pub fn advertiser_id(mut self, new_value: &str) -> CreativeListCall<'a, C, NC, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Sets the *active* query property to the given value. + /// + /// + /// Select only active creatives. Leave blank to select active and inactive creatives. + pub fn active(mut self, new_value: bool) -> CreativeListCall<'a, C, NC, A> { + self._active = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *creative* resource. +/// It is not used directly, but through a `CreativeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Creative = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creatives().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Creative, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Creative)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creatives.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Creative) -> CreativePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative ID. + pub fn id(mut self, new_value: &str) -> CreativePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one campaign by ID. +/// +/// A builder for the *get* method supported by a *campaign* resource. +/// It is not used directly, but through a `CampaignMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaigns().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CampaignGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Campaign)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaigns.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Campaign ID. + pub fn id(mut self, new_value: &str) -> CampaignGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new campaign. +/// +/// A builder for the *insert* method supported by a *campaign* resource. +/// It is not used directly, but through a `CampaignMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Campaign = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaigns().insert(&req, "profileId", "defaultLandingPageName", "defaultLandingPageUrl") +/// .doit(); +/// # } +/// ``` +pub struct CampaignInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Campaign, + _profile_id: String, + _default_landing_page_name: String, + _default_landing_page_url: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Campaign)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaigns.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("defaultLandingPageName", self._default_landing_page_name.to_string())); + params.push(("defaultLandingPageUrl", self._default_landing_page_url.to_string())); + for &field in ["alt", "profileId", "defaultLandingPageName", "defaultLandingPageUrl"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Campaign) -> CampaignInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *default landing page name* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Default landing page name for this new campaign. Must be less than 256 characters long. + pub fn default_landing_page_name(mut self, new_value: &str) -> CampaignInsertCall<'a, C, NC, A> { + self._default_landing_page_name = new_value.to_string(); + self + } + /// Sets the *default landing page url* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Default landing page URL for this new campaign. + pub fn default_landing_page_url(mut self, new_value: &str) -> CampaignInsertCall<'a, C, NC, A> { + self._default_landing_page_url = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing campaign. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *campaign* resource. +/// It is not used directly, but through a `CampaignMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Campaign = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaigns().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CampaignPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Campaign, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Campaign)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaigns.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Campaign) -> CampaignPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Campaign ID. + pub fn id(mut self, new_value: &str) -> CampaignPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing campaign. +/// +/// A builder for the *update* method supported by a *campaign* resource. +/// It is not used directly, but through a `CampaignMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Campaign = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaigns().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct CampaignUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Campaign, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Campaign)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaigns.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Campaign) -> CampaignUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of campaigns, possibly filtered. +/// +/// A builder for the *list* method supported by a *campaign* resource. +/// It is not used directly, but through a `CampaignMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.campaigns().list("profileId") +/// .subaccount_id("elitr") +/// .sort_order("et") +/// .sort_field("vero") +/// .search_string("sadipscing") +/// .page_token("sed") +/// .overridden_event_tag_id("vero") +/// .max_results(-91) +/// .add_ids("magna") +/// .add_excluded_ids("ea") +/// .at_least_one_optimization_activity(false) +/// .archived(true) +/// .add_advertiser_ids("labore") +/// .add_advertiser_group_ids("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct CampaignListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _subaccount_id: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _overridden_event_tag_id: Option, + _max_results: Option, + _ids: Vec, + _excluded_ids: Vec, + _at_least_one_optimization_activity: Option, + _archived: Option, + _advertiser_ids: Vec, + _advertiser_group_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CampaignListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CampaignListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CampaignsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.campaigns.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((16 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._subaccount_id { + params.push(("subaccountId", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._overridden_event_tag_id { + params.push(("overriddenEventTagId", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._excluded_ids.len() > 0 { + let mut s = String::new(); + for f in self._excluded_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("excludedIds", s)); + } + if let Some(value) = self._at_least_one_optimization_activity { + params.push(("atLeastOneOptimizationActivity", value.to_string())); + } + if let Some(value) = self._archived { + params.push(("archived", value.to_string())); + } + if self._advertiser_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserIds", s)); + } + if self._advertiser_group_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_group_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserGroupIds", s)); + } + for &field in ["alt", "profileId", "subaccountId", "sortOrder", "sortField", "searchString", "pageToken", "overriddenEventTagId", "maxResults", "ids", "excludedIds", "atLeastOneOptimizationActivity", "archived", "advertiserIds", "advertiserGroupIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *subaccount id* query property to the given value. + /// + /// + /// Select only campaigns that belong to this subaccount. + pub fn subaccount_id(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for campaigns by name or ID. Wildcards (*) are allowed. For example, "campaign*2015" will return campaigns with names like "campaign June 2015", "campaign April 2015" or simply "campaign 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "campaign" will match campaigns with name "my campaign", "campaign 2015" or simply "campaign". + pub fn search_string(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *overridden event tag id* query property to the given value. + /// + /// + /// Select only campaigns that have overridden this event tag ID. + pub fn overridden_event_tag_id(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._overridden_event_tag_id = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CampaignListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only campaigns with these IDs. + pub fn add_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *excluded ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Exclude campaigns with these IDs. + pub fn add_excluded_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._excluded_ids.push(new_value.to_string()); + self + } + /// Sets the *at least one optimization activity* query property to the given value. + /// + /// + /// Select only campaigns that have at least one optimization activity. + pub fn at_least_one_optimization_activity(mut self, new_value: bool) -> CampaignListCall<'a, C, NC, A> { + self._at_least_one_optimization_activity = Some(new_value); + self + } + /// Sets the *archived* query property to the given value. + /// + /// + /// Select only archived campaigns. Don't set this field to select both archived and non-archived campaigns. + pub fn archived(mut self, new_value: bool) -> CampaignListCall<'a, C, NC, A> { + self._archived = Some(new_value); + self + } + /// Append the given value to the *advertiser ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only campaigns that belong to these advertisers. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *advertiser group ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only campaigns whose advertisers belong to these advertiser groups. + pub fn add_advertiser_group_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, NC, A> { + self._advertiser_group_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CampaignListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CampaignListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing event tag. +/// +/// A builder for the *delete* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct EventTagDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event tag ID. + pub fn id(mut self, new_value: &str) -> EventTagDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of event tags, possibly filtered. +/// +/// A builder for the *list* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().list("profileId") +/// .sort_order("consetetur") +/// .sort_field("et") +/// .search_string("justo") +/// .add_ids("kasd") +/// .add_event_tag_types("kasd") +/// .enabled(true) +/// .definitions_only(true) +/// .campaign_id("nonumy") +/// .advertiser_id("sanctus") +/// .ad_id("voluptua.") +/// .doit(); +/// # } +/// ``` +pub struct EventTagListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _ids: Vec, + _event_tag_types: Vec, + _enabled: Option, + _definitions_only: Option, + _campaign_id: Option, + _advertiser_id: Option, + _ad_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EventTagsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._event_tag_types.len() > 0 { + let mut s = String::new(); + for f in self._event_tag_types.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("eventTagTypes", s)); + } + if let Some(value) = self._enabled { + params.push(("enabled", value.to_string())); + } + if let Some(value) = self._definitions_only { + params.push(("definitionsOnly", value.to_string())); + } + if let Some(value) = self._campaign_id { + params.push(("campaignId", value.to_string())); + } + if let Some(value) = self._advertiser_id { + params.push(("advertiserId", value.to_string())); + } + if let Some(value) = self._ad_id { + params.push(("adId", value.to_string())); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "ids", "eventTagTypes", "enabled", "definitionsOnly", "campaignId", "advertiserId", "adId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "eventtag*2015" will return objects with names like "eventtag June 2015", "eventtag April 2015" or simply "eventtag 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "eventtag" will match objects with name "my eventtag", "eventtag 2015" or simply "eventtag". + pub fn search_string(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only event tags with these IDs. + pub fn add_ids(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *event tag types* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only event tags with the specified event tag types. Event tag types can be used to specify whether to use a third-party pixel, a third-party JavaScript URL, or a third-party click-through URL for either impression or click tracking. + pub fn add_event_tag_types(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._event_tag_types.push(new_value.to_string()); + self + } + /// Sets the *enabled* query property to the given value. + /// + /// + /// Select only enabled event tags. When definitionsOnly is set to true, only the specified advertiser or campaign's event tags' enabledByDefault field is examined. When definitionsOnly is set to false, the specified ad or specified campaign's parent advertiser's or parent campaign's event tags' enabledByDefault and status fields are examined as well. + pub fn enabled(mut self, new_value: bool) -> EventTagListCall<'a, C, NC, A> { + self._enabled = Some(new_value); + self + } + /// Sets the *definitions only* query property to the given value. + /// + /// + /// Examine only the specified ad or campaign or advertiser's event tags for matching selector criteria. When set to false, the parent advertiser and parent campaign is examined as well. In addition, when set to false, the status field is examined as well along with the enabledByDefault field. + pub fn definitions_only(mut self, new_value: bool) -> EventTagListCall<'a, C, NC, A> { + self._definitions_only = Some(new_value); + self + } + /// Sets the *campaign id* query property to the given value. + /// + /// + /// Select only event tags that belong to this campaign. + pub fn campaign_id(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// + /// Select only event tags that belong to this advertiser. + pub fn advertiser_id(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Sets the *ad id* query property to the given value. + /// + /// + /// Select only event tags that belong to this ad. + pub fn ad_id(mut self, new_value: &str) -> EventTagListCall<'a, C, NC, A> { + self._ad_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new event tag. +/// +/// A builder for the *insert* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EventTag = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct EventTagInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: EventTag, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EventTag)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EventTag) -> EventTagInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing event tag. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EventTag = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct EventTagPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: EventTag, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EventTag)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EventTag) -> EventTagPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event tag ID. + pub fn id(mut self, new_value: &str) -> EventTagPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing event tag. +/// +/// A builder for the *update* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: EventTag = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct EventTagUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: EventTag, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EventTag)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &EventTag) -> EventTagUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one event tag by ID. +/// +/// A builder for the *get* method supported by a *eventTag* resource. +/// It is not used directly, but through a `EventTagMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.event_tags().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct EventTagGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for EventTagGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> EventTagGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EventTag)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.eventTags.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/eventTags/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> EventTagGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Event tag ID. + pub fn id(mut self, new_value: &str) -> EventTagGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EventTagGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EventTagGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of cities, possibly filtered. +/// +/// A builder for the *list* method supported by a *city* resource. +/// It is not used directly, but through a `CityMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.cities().list("profileId") +/// .add_region_dart_ids("amet") +/// .name_prefix("Lorem") +/// .add_dart_ids("eirmod") +/// .add_country_dart_ids("elitr") +/// .doit(); +/// # } +/// ``` +pub struct CityListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _region_dart_ids: Vec, + _name_prefix: Option, + _dart_ids: Vec, + _country_dart_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CityListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CityListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CitiesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.cities.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._region_dart_ids.len() > 0 { + let mut s = String::new(); + for f in self._region_dart_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("regionDartIds", s)); + } + if let Some(value) = self._name_prefix { + params.push(("namePrefix", value.to_string())); + } + if self._dart_ids.len() > 0 { + let mut s = String::new(); + for f in self._dart_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dartIds", s)); + } + if self._country_dart_ids.len() > 0 { + let mut s = String::new(); + for f in self._country_dart_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("countryDartIds", s)); + } + for &field in ["alt", "profileId", "regionDartIds", "namePrefix", "dartIds", "countryDartIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/cities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CityListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *region dart ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only cities from these regions. + pub fn add_region_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, NC, A> { + self._region_dart_ids.push(new_value.to_string()); + self + } + /// Sets the *name prefix* query property to the given value. + /// + /// + /// Select only cities with names starting with this prefix. + pub fn name_prefix(mut self, new_value: &str) -> CityListCall<'a, C, NC, A> { + self._name_prefix = Some(new_value.to_string()); + self + } + /// Append the given value to the *dart ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only cities with these DART IDs. + pub fn add_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, NC, A> { + self._dart_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *country dart ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only cities from these countries. + pub fn add_country_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, NC, A> { + self._country_dart_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CityListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CityListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CityListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of placement strategies, possibly filtered. +/// +/// A builder for the *list* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().list("profileId") +/// .sort_order("et") +/// .sort_field("eirmod") +/// .search_string("ea") +/// .page_token("et") +/// .max_results(-30) +/// .add_ids("sanctus") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementStrategiesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "placementstrategy*2015" will return objects with names like "placementstrategy June 2015", "placementstrategy April 2015" or simply "placementstrategy 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "placementstrategy" will match objects with name "my placementstrategy", "placementstrategy 2015" or simply "placementstrategy". + pub fn search_string(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> PlacementStrategyListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placement strategies with these IDs. + pub fn add_ids(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement strategy. +/// +/// A builder for the *update* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementStrategy = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementStrategy, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementStrategy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementStrategy) -> PlacementStrategyUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one placement strategy by ID. +/// +/// A builder for the *get* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementStrategy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement strategy ID. + pub fn id(mut self, new_value: &str) -> PlacementStrategyGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing placement strategy. +/// +/// A builder for the *delete* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().delete("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement strategy ID. + pub fn id(mut self, new_value: &str) -> PlacementStrategyDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new placement strategy. +/// +/// A builder for the *insert* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementStrategy = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementStrategy, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementStrategy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementStrategy) -> PlacementStrategyInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement strategy. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *placementStrategy* resource. +/// It is not used directly, but through a `PlacementStrategyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: PlacementStrategy = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placement_strategies().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementStrategy, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementStrategyPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementStrategyPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementStrategy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placementStrategies.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &PlacementStrategy) -> PlacementStrategyPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement strategy ID. + pub fn id(mut self, new_value: &str) -> PlacementStrategyPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementStrategyPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementStrategyPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of directory sites, possibly filtered. +/// +/// A builder for the *list* method supported by a *directorySite* resource. +/// It is not used directly, but through a `DirectorySiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.directory_sites().list("profileId") +/// .sort_order("sanctus") +/// .sort_field("gubergren") +/// .search_string("est") +/// .parent_id("invidunt") +/// .page_token("voluptua.") +/// .max_results(-30) +/// .add_ids("ipsum") +/// .dfp_network_code("no") +/// .country_id("vero") +/// .active(true) +/// .accepts_publisher_paid_placements(false) +/// .accepts_interstitial_placements(false) +/// .accepts_in_stream_video_placements(false) +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _parent_id: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _dfp_network_code: Option, + _country_id: Option, + _active: Option, + _accepts_publisher_paid_placements: Option, + _accepts_interstitial_placements: Option, + _accepts_in_stream_video_placements: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectorySiteListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectorySitesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.directorySites.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((16 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._parent_id { + params.push(("parentId", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._dfp_network_code { + params.push(("dfp_network_code", value.to_string())); + } + if let Some(value) = self._country_id { + params.push(("countryId", value.to_string())); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + if let Some(value) = self._accepts_publisher_paid_placements { + params.push(("acceptsPublisherPaidPlacements", value.to_string())); + } + if let Some(value) = self._accepts_interstitial_placements { + params.push(("acceptsInterstitialPlacements", value.to_string())); + } + if let Some(value) = self._accepts_in_stream_video_placements { + params.push(("acceptsInStreamVideoPlacements", value.to_string())); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "searchString", "parentId", "pageToken", "maxResults", "ids", "dfp_network_code", "countryId", "active", "acceptsPublisherPaidPlacements", "acceptsInterstitialPlacements", "acceptsInStreamVideoPlacements"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/directorySites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name, ID or URL. Wildcards (*) are allowed. For example, "directory site*2015" will return objects with names like "directory site June 2015", "directory site April 2015" or simply "directory site 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "directory site" will match objects with name "my directory site", "directory site 2015" or simply "directory site". + pub fn search_string(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *parent id* query property to the given value. + /// + /// + /// Select only directory sites with this parent ID. + pub fn parent_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._parent_id = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> DirectorySiteListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only directory sites with these IDs. + pub fn add_ids(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *dfp_network_code* query property to the given value. + /// + /// + /// Select only directory sites with this DFP network code. + pub fn dfp_network_code(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._dfp_network_code = Some(new_value.to_string()); + self + } + /// Sets the *country id* query property to the given value. + /// + /// + /// Select only directory sites with this country ID. + pub fn country_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, NC, A> { + self._country_id = Some(new_value.to_string()); + self + } + /// Sets the *active* query property to the given value. + /// + /// + /// Select only active directory sites. Leave blank to retrieve both active and inactive directory sites. + pub fn active(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, NC, A> { + self._active = Some(new_value); + self + } + /// Sets the *accepts publisher paid placements* query property to the given value. + /// + /// + /// Select only directory sites that accept publisher paid placements. This field can be left blank. + pub fn accepts_publisher_paid_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, NC, A> { + self._accepts_publisher_paid_placements = Some(new_value); + self + } + /// Sets the *accepts interstitial placements* query property to the given value. + /// + /// + /// This search filter is no longer supported and will have no effect on the results returned. + pub fn accepts_interstitial_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, NC, A> { + self._accepts_interstitial_placements = Some(new_value); + self + } + /// Sets the *accepts in stream video placements* query property to the given value. + /// + /// + /// This search filter is no longer supported and will have no effect on the results returned. + pub fn accepts_in_stream_video_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, NC, A> { + self._accepts_in_stream_video_placements = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectorySiteListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectorySiteListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one directory site by ID. +/// +/// A builder for the *get* method supported by a *directorySite* resource. +/// It is not used directly, but through a `DirectorySiteMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.directory_sites().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for DirectorySiteGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> DirectorySiteGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DirectorySite)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.directorySites.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/directorySites/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Directory site ID. + pub fn id(mut self, new_value: &str) -> DirectorySiteGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectorySiteGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectorySiteGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new size. +/// +/// A builder for the *insert* method supported by a *size* resource. +/// It is not used directly, but through a `SizeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Size; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Size = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sizes().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct SizeInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Size, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SizeInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SizeInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Size)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sizes.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sizes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Size) -> SizeInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SizeInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SizeInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SizeInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of sizes, possibly filtered. +/// +/// A builder for the *list* method supported by a *size* resource. +/// It is not used directly, but through a `SizeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sizes().list("profileId") +/// .width(-79) +/// .add_ids("dolor") +/// .iab_standard(false) +/// .height(-97) +/// .doit(); +/// # } +/// ``` +pub struct SizeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _width: Option, + _ids: Vec, + _iab_standard: Option, + _height: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SizeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SizeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SizesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sizes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._width { + params.push(("width", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._iab_standard { + params.push(("iabStandard", value.to_string())); + } + if let Some(value) = self._height { + params.push(("height", value.to_string())); + } + for &field in ["alt", "profileId", "width", "ids", "iabStandard", "height"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sizes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SizeListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *width* query property to the given value. + /// + /// + /// Select only sizes with this width. + pub fn width(mut self, new_value: i32) -> SizeListCall<'a, C, NC, A> { + self._width = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only sizes with these IDs. + pub fn add_ids(mut self, new_value: &str) -> SizeListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *iab standard* query property to the given value. + /// + /// + /// Select only IAB standard sizes. + pub fn iab_standard(mut self, new_value: bool) -> SizeListCall<'a, C, NC, A> { + self._iab_standard = Some(new_value); + self + } + /// Sets the *height* query property to the given value. + /// + /// + /// Select only sizes with this height. + pub fn height(mut self, new_value: i32) -> SizeListCall<'a, C, NC, A> { + self._height = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SizeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SizeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one size by ID. +/// +/// A builder for the *get* method supported by a *size* resource. +/// It is not used directly, but through a `SizeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.sizes().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct SizeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SizeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SizeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Size)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.sizes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/sizes/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> SizeGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Size ID. + pub fn id(mut self, new_value: &str) -> SizeGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SizeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SizeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the account's active ad summary by account ID. +/// +/// A builder for the *get* method supported by a *accountActiveAdSummary* resource. +/// It is not used directly, but through a `AccountActiveAdSummaryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_active_ad_summaries().get("profileId", "summaryAccountId") +/// .doit(); +/// # } +/// ``` +pub struct AccountActiveAdSummaryGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _summary_account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountActiveAdSummaryGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountActiveAdSummaryGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountActiveAdSummary)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountActiveAdSummaries.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("summaryAccountId", self._summary_account_id.to_string())); + for &field in ["alt", "profileId", "summaryAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountActiveAdSummaries/{summaryAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{summaryAccountId}", "summaryAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "summaryAccountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *summary account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Account ID. + pub fn summary_account_id(mut self, new_value: &str) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> { + self._summary_account_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountActiveAdSummaryGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account user profile. +/// +/// A builder for the *update* method supported by a *accountUserProfile* resource. +/// It is not used directly, but through a `AccountUserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::AccountUserProfile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountUserProfile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_user_profiles().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfileUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AccountUserProfile, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUserProfileUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUserProfileUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountUserProfile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountUserProfiles.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountUserProfile) -> AccountUserProfileUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUserProfileUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUserProfileUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of account user profiles, possibly filtered. +/// +/// A builder for the *list* method supported by a *accountUserProfile* resource. +/// It is not used directly, but through a `AccountUserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_user_profiles().list("profileId") +/// .user_role_id("dolor") +/// .subaccount_id("dolor") +/// .sort_order("dolore") +/// .sort_field("duo") +/// .search_string("ipsum") +/// .page_token("diam") +/// .max_results(-43) +/// .add_ids("et") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _user_role_id: Option, + _subaccount_id: Option, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUserProfileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUserProfileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountUserProfilesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountUserProfiles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((12 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._user_role_id { + params.push(("userRoleId", value.to_string())); + } + if let Some(value) = self._subaccount_id { + params.push(("subaccountId", value.to_string())); + } + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "userRoleId", "subaccountId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *user role id* query property to the given value. + /// + /// + /// Select only user profiles with the specified user role ID. + pub fn user_role_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._user_role_id = Some(new_value.to_string()); + self + } + /// Sets the *subaccount id* query property to the given value. + /// + /// + /// Select only user profiles with the specified subaccount ID. + pub fn subaccount_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for objects by name, ID or email. Wildcards (*) are allowed. For example, "user profile*2015" will return objects with names like "user profile June 2015", "user profile April 2015" or simply "user profile 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "user profile" will match objects with name "my user profile", "user profile 2015" or simply "user profile". + pub fn search_string(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> AccountUserProfileListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only user profiles with these IDs. + pub fn add_ids(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *active* query property to the given value. + /// + /// + /// Select only active user profiles. + pub fn active(mut self, new_value: bool) -> AccountUserProfileListCall<'a, C, NC, A> { + self._active = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUserProfileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUserProfileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing account user profile. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *accountUserProfile* resource. +/// It is not used directly, but through a `AccountUserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::AccountUserProfile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: AccountUserProfile = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_user_profiles().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfilePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AccountUserProfile, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUserProfilePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUserProfilePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountUserProfile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountUserProfiles.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &AccountUserProfile) -> AccountUserProfilePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfilePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID. + pub fn id(mut self, new_value: &str) -> AccountUserProfilePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfilePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUserProfilePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUserProfilePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one account user profile by ID. +/// +/// A builder for the *get* method supported by a *accountUserProfile* resource. +/// It is not used directly, but through a `AccountUserProfileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.account_user_profiles().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AccountUserProfileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AccountUserProfileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AccountUserProfile)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.accountUserProfiles.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/accountUserProfiles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID. + pub fn id(mut self, new_value: &str) -> AccountUserProfileGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUserProfileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUserProfileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of countries. +/// +/// A builder for the *list* method supported by a *country* resource. +/// It is not used directly, but through a `CountryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.countries().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct CountryListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CountryListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CountryListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CountriesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.countries.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/countries".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CountryListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CountryListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CountryListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CountryListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one country by ID. +/// +/// A builder for the *get* method supported by a *country* resource. +/// It is not used directly, but through a `CountryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.countries().get("profileId", "dartId") +/// .doit(); +/// # } +/// ``` +pub struct CountryGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _dart_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CountryGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CountryGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Country)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.countries.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("dartId", self._dart_id.to_string())); + for &field in ["alt", "profileId", "dartId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/countries/{dartId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{dartId}", "dartId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "dartId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CountryGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *dart id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Country DART ID. + pub fn dart_id(mut self, new_value: &str) -> CountryGetCall<'a, C, NC, A> { + self._dart_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CountryGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CountryGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CountryGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative field value. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeFieldValue = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().patch(&req, "profileId", "creativeFieldId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValuePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeFieldValue, + _profile_id: String, + _creative_field_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValuePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValuePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldValue)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "creativeFieldId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "creativeFieldId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeFieldValue) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field Value ID + pub fn id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValuePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValuePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValuePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes an existing creative field value. +/// +/// A builder for the *delete* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().delete("profileId", "creativeFieldId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _creative_field_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValueDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["profileId", "creativeFieldId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["profileId", "creativeFieldId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field Value ID + pub fn id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValueDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValueDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new creative field value. +/// +/// A builder for the *insert* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeFieldValue = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().insert(&req, "profileId", "creativeFieldId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeFieldValue, + _profile_id: String, + _creative_field_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValueInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldValue)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + for &field in ["alt", "profileId", "creativeFieldId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "creativeFieldId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeFieldValue) -> CreativeFieldValueInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueInsertCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValueInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValueInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing creative field value. +/// +/// A builder for the *update* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CreativeFieldValue = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().update(&req, "profileId", "creativeFieldId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeFieldValue, + _profile_id: String, + _creative_field_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValueUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldValue)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + for &field in ["alt", "profileId", "creativeFieldId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "creativeFieldId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CreativeFieldValue) -> CreativeFieldValueUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueUpdateCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValueUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValueUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one creative field value by ID. +/// +/// A builder for the *get* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().get("profileId", "creativeFieldId", "id") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _creative_field_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValueGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldValue)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "creativeFieldId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["profileId", "creativeFieldId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative Field Value ID + pub fn id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValueGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValueGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of creative field values, possibly filtered. +/// +/// A builder for the *list* method supported by a *creativeFieldValue* resource. +/// It is not used directly, but through a `CreativeFieldValueMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.creative_field_values().list("profileId", "creativeFieldId") +/// .sort_order("et") +/// .sort_field("sanctus") +/// .search_string("diam") +/// .page_token("eos") +/// .max_results(-38) +/// .add_ids("sea") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _creative_field_id: String, + _sort_order: Option, + _sort_field: Option, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CreativeFieldValueListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CreativeFieldValueListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreativeFieldValuesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.creativeFieldValues.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("creativeFieldId", self._creative_field_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + for &field in ["alt", "profileId", "creativeFieldId", "sortOrder", "sortField", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{creativeFieldId}", "creativeFieldId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "creativeFieldId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *creative field id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Creative field ID for this creative field value. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for creative field values by their values. Wildcards (e.g. *) are not allowed. + pub fn search_string(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only creative field values with these IDs. + pub fn add_ids(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CreativeFieldValueListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CreativeFieldValueListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a report. +/// +/// A builder for the *update* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Report = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().update(&req, "profileId", "reportId") +/// .doit(); +/// # } +/// ``` +pub struct ReportUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + for &field in ["alt", "profileId", "reportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Report) -> ReportUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportUpdateCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Runs a report. +/// +/// A builder for the *run* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().run("profileId", "reportId") +/// .synchronous(true) +/// .doit(); +/// # } +/// ``` +pub struct ReportRunCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _report_id: String, + _synchronous: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportRunCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportRunCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.run", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + if let Some(value) = self._synchronous { + params.push(("synchronous", value.to_string())); + } + for &field in ["alt", "profileId", "reportId", "synchronous"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}/run".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportRunCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportRunCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *synchronous* query property to the given value. + /// + /// + /// If set and true, tries to run the report synchronously. + pub fn synchronous(mut self, new_value: bool) -> ReportRunCall<'a, C, NC, A> { + self._synchronous = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportRunCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportRunCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportRunCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a report. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Report = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().patch(&req, "profileId", "reportId") +/// .doit(); +/// # } +/// ``` +pub struct ReportPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + for &field in ["alt", "profileId", "reportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Report) -> ReportPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportPatchCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists files for a report. +/// +/// A builder for the *files.list* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().files_list("profileId", "reportId") +/// .sort_order("accusam") +/// .sort_field("sed") +/// .page_token("sea") +/// .max_results(-1) +/// .doit(); +/// # } +/// ``` +pub struct ReportFileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _report_id: String, + _sort_order: Option, + _sort_field: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportFileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportFileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FileList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.files.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "profileId", "reportId", "sortOrder", "sortField", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}/files".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportFileListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the parent report. + pub fn report_id(mut self, new_value: &str) -> ReportFileListCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is 'DESCENDING'. + pub fn sort_order(mut self, new_value: &str) -> ReportFileListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// The field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> ReportFileListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> ReportFileListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> ReportFileListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportFileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportFileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportFileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a report. +/// +/// A builder for the *insert* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Report = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ReportInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Report) -> ReportInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the fields that are compatible to be selected in the respective sections of a report criteria, given the fields already selected in the input report and user permissions. +/// +/// A builder for the *compatibleFields.query* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Report = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().compatible_fields_query(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct ReportCompatibleFieldQueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportCompatibleFieldQueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportCompatibleFieldQueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CompatibleFields)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.compatibleFields.query", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/compatiblefields/query".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Report) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportCompatibleFieldQueryCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a report by its ID. +/// +/// A builder for the *get* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().get("profileId", "reportId") +/// .doit(); +/// # } +/// ``` +pub struct ReportGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + for &field in ["alt", "profileId", "reportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportGetCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a report file. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `File` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *files.get* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().files_get("profileId", "reportId", "fileId") +/// .doit(); +/// # } +/// ``` +pub struct ReportFileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _report_id: String, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportFileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportFileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.files.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["profileId", "reportId", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId"), ("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["profileId", "reportId", "fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report file. + pub fn file_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportFileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportFileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportFileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a report by its ID. +/// +/// A builder for the *delete* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().delete("profileId", "reportId") +/// .doit(); +/// # } +/// ``` +pub struct ReportDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + for &field in ["profileId", "reportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportDeleteCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportDeleteCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves list of reports. +/// +/// A builder for the *list* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().list("profileId") +/// .sort_order("dolor") +/// .sort_field("consetetur") +/// .scope("sadipscing") +/// .page_token("ipsum") +/// .max_results(-17) +/// .doit(); +/// # } +/// ``` +pub struct ReportListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _scope: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ReportList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.reports.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if let Some(value) = self._scope { + params.push(("scope", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "scope", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The DFA user profile ID. + pub fn profile_id(mut self, new_value: &str) -> ReportListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is 'DESCENDING'. + pub fn sort_order(mut self, new_value: &str) -> ReportListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// The field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> ReportListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Sets the *scope* query property to the given value. + /// + /// + /// The scope that defines which results are returned, default is 'MINE'. + pub fn scope(mut self, new_value: &str) -> ReportListCall<'a, C, NC, A> { + self._scope = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The value of the nextToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> ReportListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> ReportListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of browsers. +/// +/// A builder for the *list* method supported by a *browser* resource. +/// It is not used directly, but through a `BrowserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.browsers().list("profileId") +/// .doit(); +/// # } +/// ``` +pub struct BrowserListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for BrowserListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> BrowserListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BrowsersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.browsers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/browsers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> BrowserListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BrowserListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BrowserListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BrowserListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Placement = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().patch(&req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Placement, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Placement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Placement) -> PlacementPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementPatchCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement ID. + pub fn id(mut self, new_value: &str) -> PlacementPatchCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of placements, possibly filtered. +/// +/// A builder for the *list* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().list("profileId") +/// .sort_order("et") +/// .sort_field("amet") +/// .add_size_ids("sit") +/// .add_site_ids("vero") +/// .search_string("nonumy") +/// .add_pricing_types("accusam") +/// .add_placement_strategy_ids("est") +/// .payment_source("sit") +/// .page_token("erat") +/// .max_results(-25) +/// .add_ids("accusam") +/// .add_group_ids("et") +/// .add_directory_site_ids("clita") +/// .add_content_category_ids("tempor") +/// .add_compatibilities("ut") +/// .add_campaign_ids("kasd") +/// .archived(false) +/// .add_advertiser_ids("ut") +/// .doit(); +/// # } +/// ``` +pub struct PlacementListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _sort_order: Option, + _sort_field: Option, + _size_ids: Vec, + _site_ids: Vec, + _search_string: Option, + _pricing_types: Vec, + _placement_strategy_ids: Vec, + _payment_source: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _group_ids: Vec, + _directory_site_ids: Vec, + _content_category_ids: Vec, + _compatibilities: Vec, + _campaign_ids: Vec, + _archived: Option, + _advertiser_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((21 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_field { + params.push(("sortField", value.to_string())); + } + if self._size_ids.len() > 0 { + let mut s = String::new(); + for f in self._size_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("sizeIds", s)); + } + if self._site_ids.len() > 0 { + let mut s = String::new(); + for f in self._site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("siteIds", s)); + } + if let Some(value) = self._search_string { + params.push(("searchString", value.to_string())); + } + if self._pricing_types.len() > 0 { + let mut s = String::new(); + for f in self._pricing_types.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pricingTypes", s)); + } + if self._placement_strategy_ids.len() > 0 { + let mut s = String::new(); + for f in self._placement_strategy_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("placementStrategyIds", s)); + } + if let Some(value) = self._payment_source { + params.push(("paymentSource", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if self._ids.len() > 0 { + let mut s = String::new(); + for f in self._ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("ids", s)); + } + if self._group_ids.len() > 0 { + let mut s = String::new(); + for f in self._group_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("groupIds", s)); + } + if self._directory_site_ids.len() > 0 { + let mut s = String::new(); + for f in self._directory_site_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("directorySiteIds", s)); + } + if self._content_category_ids.len() > 0 { + let mut s = String::new(); + for f in self._content_category_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("contentCategoryIds", s)); + } + if self._compatibilities.len() > 0 { + let mut s = String::new(); + for f in self._compatibilities.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("compatibilities", s)); + } + if self._campaign_ids.len() > 0 { + let mut s = String::new(); + for f in self._campaign_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("campaignIds", s)); + } + if let Some(value) = self._archived { + params.push(("archived", value.to_string())); + } + if self._advertiser_ids.len() > 0 { + let mut s = String::new(); + for f in self._advertiser_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("advertiserIds", s)); + } + for &field in ["alt", "profileId", "sortOrder", "sortField", "sizeIds", "siteIds", "searchString", "pricingTypes", "placementStrategyIds", "paymentSource", "pageToken", "maxResults", "ids", "groupIds", "directorySiteIds", "contentCategoryIds", "compatibilities", "campaignIds", "archived", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Order of sorted results, default is ASCENDING. + pub fn sort_order(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort field* query property to the given value. + /// + /// + /// Field by which to sort the list. + pub fn sort_field(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Append the given value to the *size ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these sizes. + pub fn add_size_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these sites. + pub fn add_site_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._site_ids.push(new_value.to_string()); + self + } + /// Sets the *search string* query property to the given value. + /// + /// + /// Allows searching for placements by name or ID. Wildcards (*) are allowed. For example, "placement*2015" will return placements with names like "placement June 2015", "placement May 2015" or simply "placements 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "placement" will match placements with name "my placement", "placement 2015" or simply "placement". + pub fn search_string(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Append the given value to the *pricing types* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements with these pricing types. + pub fn add_pricing_types(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._pricing_types.push(new_value.to_string()); + self + } + /// Append the given value to the *placement strategy ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these placement strategies. + pub fn add_placement_strategy_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._placement_strategy_ids.push(new_value.to_string()); + self + } + /// Sets the *payment source* query property to the given value. + /// + /// + /// Select only placements with this payment source. + pub fn payment_source(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._payment_source = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Value of the nextPageToken from the previous result page. + pub fn page_token(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn max_results(mut self, new_value: i32) -> PlacementListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Append the given value to the *ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements with these IDs. + pub fn add_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._ids.push(new_value.to_string()); + self + } + /// Append the given value to the *group ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that belong to these placement groups. + pub fn add_group_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._group_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *directory site ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these directory sites. + pub fn add_directory_site_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *content category ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these content categories. + pub fn add_content_category_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._content_category_ids.push(new_value.to_string()); + self + } + /// Append the given value to the *compatibilities* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that are associated with these compatibilities. WEB and WEB_INTERSTITIAL refer to rendering either on desktop or on mobile devices for regular or interstitial ads respectively. APP and APP_INTERSTITIAL are for rendering in mobile apps.IN_STREAM_VIDEO refers to rendering in in-stream video ads developed with the VAST standard. + pub fn add_compatibilities(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._compatibilities.push(new_value.to_string()); + self + } + /// Append the given value to the *campaign ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that belong to these campaigns. + pub fn add_campaign_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Sets the *archived* query property to the given value. + /// + /// + /// Select only archived placements. Don't set this field to select both archived and non-archived placements. + pub fn archived(mut self, new_value: bool) -> PlacementListCall<'a, C, NC, A> { + self._archived = Some(new_value); + self + } + /// Append the given value to the *advertiser ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Select only placements that belong to these advertisers. + pub fn add_advertiser_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, NC, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets one placement by ID. +/// +/// A builder for the *get* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Placement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{id}", "id")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["profileId", "id"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGetCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Placement ID. + pub fn id(mut self, new_value: &str) -> PlacementGetCall<'a, C, NC, A> { + self._id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a new placement. +/// +/// A builder for the *insert* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Placement = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().insert(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Placement, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Placement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Placement) -> PlacementInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementInsertCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing placement. +/// +/// A builder for the *update* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// use dfareporting2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Placement = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().update(&req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct PlacementUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Placement, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Placement)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + for &field in ["alt", "profileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Placement) -> PlacementUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementUpdateCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generates tags for a placement. +/// +/// A builder for the *generatetags* method supported by a *placement* resource. +/// It is not used directly, but through a `PlacementMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dfareporting2" as dfareporting2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2::Dfareporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dfareporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.placements().generatetags("profileId") +/// .add_tag_formats("no") +/// .add_placement_ids("takimata") +/// .campaign_id("takimata") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGeneratetagCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _tag_formats: Vec, + _placement_ids: Vec, + _campaign_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PlacementGeneratetagCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PlacementGeneratetagCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlacementsGenerateTagsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dfareporting.placements.generatetags", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("profileId", self._profile_id.to_string())); + if self._tag_formats.len() > 0 { + let mut s = String::new(); + for f in self._tag_formats.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("tagFormats", s)); + } + if self._placement_ids.len() > 0 { + let mut s = String::new(); + for f in self._placement_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("placementIds", s)); + } + if let Some(value) = self._campaign_id { + params.push(("campaignId", value.to_string())); + } + for &field in ["alt", "profileId", "tagFormats", "placementIds", "campaignId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dfareporting/v2.0/userprofiles/{profileId}/placements/generatetags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["profileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *profile id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// User profile ID associated with this request. + pub fn profile_id(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, NC, A> { + self._profile_id = new_value.to_string(); + self + } + /// Append the given value to the *tag formats* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Tag formats to generate for these placements. + pub fn add_tag_formats(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, NC, A> { + self._tag_formats.push(new_value.to_string()); + self + } + /// Append the given value to the *placement ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Generate tags for these placements. + pub fn add_placement_ids(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, NC, A> { + self._placement_ids.push(new_value.to_string()); + self + } + /// Sets the *campaign id* query property to the given value. + /// + /// + /// Generate placements belonging to this campaign. This is a required field. + pub fn campaign_id(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, NC, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGeneratetagCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlacementGeneratetagCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlacementGeneratetagCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/dns1_beta1/Cargo.toml b/gen/dns1_beta1/Cargo.toml new file mode 100644 index 0000000000..ac08932857 --- /dev/null +++ b/gen/dns1_beta1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-dns1_beta1" +version = "0.1.0+20150114" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with dns (protocol v1beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dns1_beta1" +homepage = "https://developers.google.com/cloud-dns" +documentation = "http://byron.github.io/google-apis-rs/google-dns1_beta1" +license = "MIT" +keywords = ["dns", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/dns1_beta1/LICENSE.md b/gen/dns1_beta1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/dns1_beta1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/dns1_beta1/README.md b/gen/dns1_beta1/README.md new file mode 100644 index 0000000000..80fe861190 --- /dev/null +++ b/gen/dns1_beta1/README.md @@ -0,0 +1,174 @@ + +The `google-dns1_beta1` library allows access to all features of the *Google dns* service. + +This documentation was generated from *dns* crate version *0.1.0+20150114*, where *20150114* is the exact revision of the *dns:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *dns* *v1_beta1* API can be found at the +[official documentation site](https://developers.google.com/cloud-dns). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.Dns.html) ... + +* [changes](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.Change.html) + * [*create*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ChangeCreateCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ChangeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ChangeListCall.html) +* [managed zones](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ManagedZone.html) + * [*create*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ManagedZoneCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ManagedZoneDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ManagedZoneGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ManagedZoneListCall.html) +* [projects](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.Project.html) + * [*get*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ProjectGetCall.html) +* [resource record sets](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ResourceRecordSet.html) + * [*list*](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.ResourceRecordSetListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-dns1_beta1/struct.Dns.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.managed_zones().get(...).doit() +let r = hub.managed_zones().list(...).doit() +let r = hub.managed_zones().create(...).doit() +let r = hub.managed_zones().delete(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-dns1_beta1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-dns1_beta1" as dns1_beta1; +use dns1_beta1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use dns1_beta1::Dns; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Dns::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.managed_zones().list("project") + .page_token("sit") + .max_results(-65) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-dns1_beta1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-dns1_beta1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-dns1_beta1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-dns1_beta1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **dns1_beta1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/dns1_beta1/src/cmn.rs b/gen/dns1_beta1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/dns1_beta1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/dns1_beta1/src/lib.rs b/gen/dns1_beta1/src/lib.rs new file mode 100644 index 0000000000..5f485ee069 --- /dev/null +++ b/gen/dns1_beta1/src/lib.rs @@ -0,0 +1,3226 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *dns* crate version *0.1.0+20150114*, where *20150114* is the exact revision of the *dns:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *dns* *v1_beta1* API can be found at the +//! [official documentation site](https://developers.google.com/cloud-dns). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/dns1_beta1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Dns.html) ... +//! +//! * [changes](struct.Change.html) +//! * [*create*](struct.ChangeCreateCall.html), [*get*](struct.ChangeGetCall.html) and [*list*](struct.ChangeListCall.html) +//! * [managed zones](struct.ManagedZone.html) +//! * [*create*](struct.ManagedZoneCreateCall.html), [*delete*](struct.ManagedZoneDeleteCall.html), [*get*](struct.ManagedZoneGetCall.html) and [*list*](struct.ManagedZoneListCall.html) +//! * [projects](struct.Project.html) +//! * [*get*](struct.ProjectGetCall.html) +//! * [resource record sets](struct.ResourceRecordSet.html) +//! * [*list*](struct.ResourceRecordSetListCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Dns.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.managed_zones().get(...).doit() +//! let r = hub.managed_zones().list(...).doit() +//! let r = hub.managed_zones().create(...).doit() +//! let r = hub.managed_zones().delete(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-dns1_beta1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-dns1_beta1" as dns1_beta1; +//! use dns1_beta1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use dns1_beta1::Dns; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Dns::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.managed_zones().list("project") +//! .page_token("et") +//! .max_results(-18) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View your DNS records hosted by Google Cloud DNS + NdevClouddnReadonly, + + /// View and manage your DNS records hosted by Google Cloud DNS + NdevClouddnReadwrite, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::NdevClouddnReadonly => "https://www.googleapis.com/auth/ndev.clouddns.readonly", + Scope::NdevClouddnReadwrite => "https://www.googleapis.com/auth/ndev.clouddns.readwrite", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::NdevClouddnReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Dns related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dns1_beta1" as dns1_beta1; +/// use dns1_beta1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dns1_beta1::Dns; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.managed_zones().list("project") +/// .page_token("accusam") +/// .max_results(-8) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Dns { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Dns {} + +impl<'a, C, NC, A> Dns + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Dns { + Dns { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn changes(&'a self) -> ChangeMethods<'a, C, NC, A> { + ChangeMethods { hub: &self } + } + pub fn managed_zones(&'a self) -> ManagedZoneMethods<'a, C, NC, A> { + ManagedZoneMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, NC, A> { + ProjectMethods { hub: &self } + } + pub fn resource_record_sets(&'a self) -> ResourceRecordSetMethods<'a, C, NC, A> { + ResourceRecordSetMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A zone is a subtree of the DNS namespace under one administrative responsibility. A ManagedZone is a resource that represents a DNS zone hosted by the Cloud DNS service. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get managed zones](struct.ManagedZoneGetCall.html) (response) +/// * [list managed zones](struct.ManagedZoneListCall.html) (none) +/// * [create managed zones](struct.ManagedZoneCreateCall.html) (request|response) +/// * [delete managed zones](struct.ManagedZoneDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ManagedZone { + /// Identifies what kind of resource this is. Value: the fixed string "dns#managedZone". + pub kind: Option, + /// A mutable string of at most 1024 characters associated with this resource for the user's convenience. Has no effect on the managed zone's function. + pub description: Option, + /// Delegate your managed_zone to these virtual name servers; defined by the server (output only) + #[serde(alias="nameServers")] + pub name_servers: Option>, + /// The time that this resource was created on the server. This is in RFC3339 text format. Output only. + #[serde(alias="creationTime")] + pub creation_time: Option, + /// Unique identifier for the resource; defined by the server (output only) + pub id: Option, + /// The DNS name of this managed zone, for instance "example.com.". + #[serde(alias="dnsName")] + pub dns_name: Option, + /// Optionally specifies the NameServerSet for this ManagedZone. A NameServerSet is a set of DNS name servers that all host the same ManagedZones. Most users will leave this field unset. + #[serde(alias="nameServerSet")] + pub name_server_set: Option, + /// User assigned name for this resource. Must be unique within the project. The name must be 1-32 characters long, must begin with a letter, end with a letter or digit, and only contain lowercase letters, digits or dashes. + pub name: Option, +} + +impl RequestValue for ManagedZone {} +impl Resource for ManagedZone {} +impl ResponseResult for ManagedZone {} + + +/// A unit of data that will be returned by the DNS servers. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list resource record sets](struct.ResourceRecordSetListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ResourceRecordSet { + /// As defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1) + pub rrdatas: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dns#resourceRecordSet". + pub kind: Option, + /// One of A, AAAA, SOA, MX, NS, TXT + #[serde(alias="type")] + pub type_: Option, + /// For example, www.example.com. + pub name: Option, + /// Number of seconds that this ResourceRecordSet can be cached by resolvers. + pub ttl: Option, +} + +impl Resource for ResourceRecordSet {} + + +/// Limits associated with a Project. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Quota { + /// Maximum allowed number of ResourceRecordSets per zone in the project. + #[serde(alias="rrsetsPerManagedZone")] + pub rrsets_per_managed_zone: i32, + /// Identifies what kind of resource this is. Value: the fixed string "dns#quota". + pub kind: String, + /// Maximum allowed number of ResourceRecordSets to add per ChangesCreateRequest. + #[serde(alias="rrsetAdditionsPerChange")] + pub rrset_additions_per_change: i32, + /// Maximum allowed size for total rrdata in one ChangesCreateRequest in bytes. + #[serde(alias="totalRrdataSizePerChange")] + pub total_rrdata_size_per_change: i32, + /// Maximum allowed number of ResourceRecords per ResourceRecordSet. + #[serde(alias="resourceRecordsPerRrset")] + pub resource_records_per_rrset: i32, + /// Maximum allowed number of ResourceRecordSets to delete per ChangesCreateRequest. + #[serde(alias="rrsetDeletionsPerChange")] + pub rrset_deletions_per_change: i32, + /// Maximum allowed number of managed zones in the project. + #[serde(alias="managedZones")] + pub managed_zones: i32, +} + +impl Part for Quota {} + + +/// A project resource. The project is a top level container for resources including Cloud DNS ManagedZones. Projects can be created only in the APIs console. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get projects](struct.ProjectGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Project { + /// Quotas assigned to this project (output only). + pub quota: Quota, + /// Identifies what kind of resource this is. Value: the fixed string "dns#project". + pub kind: String, + /// User assigned unique identifier for the resource (output only). + pub id: String, + /// Unique numeric identifier for the resource; defined by the server (output only). + pub number: String, +} + +impl Resource for Project {} +impl ResponseResult for Project {} + + +/// The response to a request to enumerate Changes to a ResourceRecordSets collection. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list changes](struct.ChangeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChangesListResponse { + /// The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your pagination token. + /// + /// In this way you can retrieve the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned will be an inconsistent view of the collection. There is no way to retrieve a "snapshot" of collections larger than the maximum page size. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Type of resource. + pub kind: String, + /// The requested changes. + pub changes: Vec, +} + +impl ResponseResult for ChangesListResponse {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list managed zones](struct.ManagedZoneListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ManagedZonesListResponse { + /// The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your page token. + /// + /// In this way you can retrieve the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned will be an inconsistent view of the collection. There is no way to retrieve a consistent snapshot of a collection larger than the maximum page size. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// Type of resource. + pub kind: String, + /// The managed zone resources. + #[serde(alias="managedZones")] + pub managed_zones: Vec, +} + +impl ResponseResult for ManagedZonesListResponse {} + + +/// An atomic update to a collection of ResourceRecordSets. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get changes](struct.ChangeGetCall.html) (response) +/// * [create changes](struct.ChangeCreateCall.html) (request|response) +/// * [list changes](struct.ChangeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Change { + /// Which ResourceRecordSets to remove? Must match existing data exactly. + pub deletions: Option>, + /// Status of the operation. Can be one of the following: "PENDING" or "DONE" (output only). + pub status: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dns#change". + pub kind: Option, + /// The time that this operation was started by the server. This is in RFC3339 text format. + #[serde(alias="startTime")] + pub start_time: Option, + /// Which ResourceRecordSets to add? + pub additions: Option>, + /// Unique identifier for the resource; defined by the server (output only). + pub id: Option, +} + +impl RequestValue for Change {} +impl Resource for Change {} +impl ResponseResult for Change {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list resource record sets](struct.ResourceRecordSetListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ResourceRecordSetsListResponse { + /// The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your pagination token. + /// + /// In this way you can retrieve the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned will be an inconsistent view of the collection. There is no way to retrieve a consistent snapshot of a collection larger than the maximum page size. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// The resource record set resources. + pub rrsets: Vec, + /// Type of resource. + pub kind: String, +} + +impl ResponseResult for ResourceRecordSetsListResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *change* resources. +/// It is not used directly, but through the `Dns` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dns1_beta1" as dns1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dns1_beta1::Dns; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dns::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.changes(); +/// # } +/// ``` +pub struct ChangeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChangeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Atomically update the ResourceRecordSet collection. + pub fn create(&self, request: &Change, project: &str, managed_zone: &str) -> ChangeCreateCall<'a, C, NC, A> { + ChangeCreateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Enumerate Changes to a ResourceRecordSet collection. + pub fn list(&self, project: &str, managed_zone: &str) -> ChangeListCall<'a, C, NC, A> { + ChangeListCall { + hub: self.hub, + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _sort_order: Default::default(), + _sort_by: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetch the representation of an existing Change. + pub fn get(&self, project: &str, managed_zone: &str, change_id: &str) -> ChangeGetCall<'a, C, NC, A> { + ChangeGetCall { + hub: self.hub, + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _change_id: change_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *managedZone* resources. +/// It is not used directly, but through the `Dns` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dns1_beta1" as dns1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dns1_beta1::Dns; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dns::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create(...)`, `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.managed_zones(); +/// # } +/// ``` +pub struct ManagedZoneMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ManagedZoneMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagedZoneMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Create a new ManagedZone. + pub fn create(&self, request: &ManagedZone, project: &str) -> ManagedZoneCreateCall<'a, C, NC, A> { + ManagedZoneCreateCall { + hub: self.hub, + _request: request.clone(), + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Delete a previously created ManagedZone. + pub fn delete(&self, project: &str, managed_zone: &str) -> ManagedZoneDeleteCall<'a, C, NC, A> { + ManagedZoneDeleteCall { + hub: self.hub, + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetch the representation of an existing ManagedZone. + pub fn get(&self, project: &str, managed_zone: &str) -> ManagedZoneGetCall<'a, C, NC, A> { + ManagedZoneGetCall { + hub: self.hub, + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Enumerate ManagedZones that have been created but not yet deleted. + pub fn list(&self, project: &str) -> ManagedZoneListCall<'a, C, NC, A> { + ManagedZoneListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *resourceRecordSet* resources. +/// It is not used directly, but through the `Dns` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dns1_beta1" as dns1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dns1_beta1::Dns; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dns::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.resource_record_sets(); +/// # } +/// ``` +pub struct ResourceRecordSetMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ResourceRecordSetMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ResourceRecordSetMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Enumerate ResourceRecordSets that have been created but not yet deleted. + pub fn list(&self, project: &str, managed_zone: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + ResourceRecordSetListCall { + hub: self.hub, + _project: project.to_string(), + _managed_zone: managed_zone.to_string(), + _type_: Default::default(), + _page_token: Default::default(), + _name: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *project* resources. +/// It is not used directly, but through the `Dns` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-dns1_beta1" as dns1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dns1_beta1::Dns; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Dns::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ProjectMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Fetch the representation of an existing Project. + pub fn get(&self, project: &str) -> ProjectGetCall<'a, C, NC, A> { + ProjectGetCall { + hub: self.hub, + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Atomically update the ResourceRecordSet collection. +/// +/// A builder for the *create* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// use dns1_beta1::Change; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Change = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().create(&req, "project", "managedZone") +/// .doit(); +/// # } +/// ``` +pub struct ChangeCreateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _request: Change, + _project: String, + _managed_zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeCreateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeCreateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Change)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.changes.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + for &field in ["alt", "project", "managedZone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}/changes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "managedZone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Change) -> ChangeCreateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ChangeCreateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ChangeCreateCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeCreateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeCreateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeCreateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Enumerate Changes to a ResourceRecordSet collection. +/// +/// A builder for the *list* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().list("project", "managedZone") +/// .sort_order("sea") +/// .sort_by("nonumy") +/// .page_token("dolores") +/// .max_results(-61) +/// .doit(); +/// # } +/// ``` +pub struct ChangeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _managed_zone: String, + _sort_order: Option, + _sort_by: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChangesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.changes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + if let Some(value) = self._sort_order { + params.push(("sortOrder", value.to_string())); + } + if let Some(value) = self._sort_by { + params.push(("sortBy", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "managedZone", "sortOrder", "sortBy", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}/changes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "managedZone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *sort order* query property to the given value. + /// + /// + /// Sorting order direction: 'ascending' or 'descending'. + pub fn sort_order(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Sets the *sort by* query property to the given value. + /// + /// + /// Sorting criterion. The only supported value is change sequence. + pub fn sort_by(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._sort_by = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. A tag returned by a previous list request that was truncated. Use this parameter to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum number of results to be returned. If unspecified, the server will decide how many results to return. + pub fn max_results(mut self, new_value: i32) -> ChangeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetch the representation of an existing Change. +/// +/// A builder for the *get* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().get("project", "managedZone", "changeId") +/// .doit(); +/// # } +/// ``` +pub struct ChangeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _managed_zone: String, + _change_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Change)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.changes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + params.push(("changeId", self._change_id.to_string())); + for &field in ["alt", "project", "managedZone", "changeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}/changes/{changeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone"), ("{changeId}", "changeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["project", "managedZone", "changeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ChangeGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ChangeGetCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *change id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The identifier of the requested change, from a previous ResourceRecordSetsChangeResponse. + pub fn change_id(mut self, new_value: &str) -> ChangeGetCall<'a, C, NC, A> { + self._change_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Create a new ManagedZone. +/// +/// A builder for the *create* method supported by a *managedZone* resource. +/// It is not used directly, but through a `ManagedZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// use dns1_beta1::ManagedZone; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ManagedZone = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.managed_zones().create(&req, "project") +/// .doit(); +/// # } +/// ``` +pub struct ManagedZoneCreateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _request: ManagedZone, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagedZoneCreateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagedZoneCreateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ManagedZone)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.managedZones.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ManagedZone) -> ManagedZoneCreateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ManagedZoneCreateCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagedZoneCreateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagedZoneCreateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagedZoneCreateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Delete a previously created ManagedZone. +/// +/// A builder for the *delete* method supported by a *managedZone* resource. +/// It is not used directly, but through a `ManagedZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.managed_zones().delete("project", "managedZone") +/// .doit(); +/// # } +/// ``` +pub struct ManagedZoneDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _managed_zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagedZoneDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagedZoneDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.managedZones.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + for &field in ["project", "managedZone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "managedZone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ManagedZoneDeleteCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ManagedZoneDeleteCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagedZoneDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagedZoneDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagedZoneDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetch the representation of an existing ManagedZone. +/// +/// A builder for the *get* method supported by a *managedZone* resource. +/// It is not used directly, but through a `ManagedZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.managed_zones().get("project", "managedZone") +/// .doit(); +/// # } +/// ``` +pub struct ManagedZoneGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _managed_zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagedZoneGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagedZoneGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ManagedZone)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.managedZones.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + for &field in ["alt", "project", "managedZone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "managedZone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ManagedZoneGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ManagedZoneGetCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagedZoneGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagedZoneGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagedZoneGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Enumerate ManagedZones that have been created but not yet deleted. +/// +/// A builder for the *list* method supported by a *managedZone* resource. +/// It is not used directly, but through a `ManagedZoneMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.managed_zones().list("project") +/// .page_token("ipsum") +/// .max_results(-5) +/// .doit(); +/// # } +/// ``` +pub struct ManagedZoneListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ManagedZoneListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ManagedZoneListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ManagedZonesListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.managedZones.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ManagedZoneListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. A tag returned by a previous list request that was truncated. Use this parameter to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ManagedZoneListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum number of results to be returned. If unspecified, the server will decide how many results to return. + pub fn max_results(mut self, new_value: i32) -> ManagedZoneListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManagedZoneListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ManagedZoneListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ManagedZoneListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Enumerate ResourceRecordSets that have been created but not yet deleted. +/// +/// A builder for the *list* method supported by a *resourceRecordSet* resource. +/// It is not used directly, but through a `ResourceRecordSetMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.resource_record_sets().list("project", "managedZone") +/// .type_("aliquyam") +/// .page_token("sea") +/// .name("Lorem") +/// .max_results(-75) +/// .doit(); +/// # } +/// ``` +pub struct ResourceRecordSetListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _managed_zone: String, + _type_: Option, + _page_token: Option, + _name: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ResourceRecordSetListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ResourceRecordSetListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ResourceRecordSetsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.resourceRecordSets.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("managedZone", self._managed_zone.to_string())); + if let Some(value) = self._type_ { + params.push(("type", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "project", "managedZone", "type", "pageToken", "name", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}/managedZones/{managedZone}/rrsets".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{managedZone}", "managedZone")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["project", "managedZone"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *managed zone* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the managed zone addressed by this request. Can be the managed zone name or id. + pub fn managed_zone(mut self, new_value: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._managed_zone = new_value.to_string(); + self + } + /// Sets the *type* query property to the given value. + /// + /// + /// Restricts the list to return only records of this type. If present, the "name" parameter must also be present. + pub fn type_(mut self, new_value: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._type_ = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Optional. A tag returned by a previous list request that was truncated. Use this parameter to continue a previous list request. + pub fn page_token(mut self, new_value: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *name* query property to the given value. + /// + /// + /// Restricts the list to return only records with this fully qualified domain name. + pub fn name(mut self, new_value: &str) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._name = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Optional. Maximum number of results to be returned. If unspecified, the server will decide how many results to return. + pub fn max_results(mut self, new_value: i32) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ResourceRecordSetListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ResourceRecordSetListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ResourceRecordSetListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Fetch the representation of an existing Project. +/// +/// A builder for the *get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-dns1_beta1" as dns1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dns1_beta1::Dns; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Dns::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.projects().get("project") +/// .doit(); +/// # } +/// ``` +pub struct ProjectGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Dns, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ProjectGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ProjectGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Project)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "dns.projects.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + for &field in ["alt", "project"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/dns/v1beta1/projects/{project}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevClouddnReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *project* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Identifies the project addressed by this request. + pub fn project(mut self, new_value: &str) -> ProjectGetCall<'a, C, NC, A> { + self._project = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ProjectGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/doubleclickbidmanager1/Cargo.toml b/gen/doubleclickbidmanager1/Cargo.toml new file mode 100644 index 0000000000..8840495bea --- /dev/null +++ b/gen/doubleclickbidmanager1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-doubleclickbidmanager1" +version = "0.1.0+20150122" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with DoubleClick Bid Manager (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/doubleclickbidmanager1" +homepage = "https://developers.google.com/bid-manager/" +documentation = "http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1" +license = "MIT" +keywords = ["doubleclickbidmanager", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/doubleclickbidmanager1/LICENSE.md b/gen/doubleclickbidmanager1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/doubleclickbidmanager1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/doubleclickbidmanager1/README.md b/gen/doubleclickbidmanager1/README.md new file mode 100644 index 0000000000..dddb2ec847 --- /dev/null +++ b/gen/doubleclickbidmanager1/README.md @@ -0,0 +1,168 @@ + +The `google-doubleclickbidmanager1` library allows access to all features of the *Google DoubleClick Bid Manager* service. + +This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.0+20150122*, where *20150122* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *DoubleClick Bid Manager* *v1* API can be found at the +[official documentation site](https://developers.google.com/bid-manager/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.DoubleClickBidManager.html) ... + +* lineitems + * [*downloadlineitems*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.LineitemDownloadlineitemCall.html) and [*uploadlineitems*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.LineitemUploadlineitemCall.html) +* [queries](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.Query.html) + * [*createquery*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.QueryCreatequeryCall.html), [*deletequery*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.QueryDeletequeryCall.html), [*getquery*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.QueryGetqueryCall.html), [*listqueries*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.QueryListqueryCall.html) and [*runquery*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.QueryRunqueryCall.html) +* [reports](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.Report.html) + * [*listreports*](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.ReportListreportCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/struct.DoubleClickBidManager.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.queries().getquery(...).doit() +let r = hub.queries().createquery(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-doubleclickbidmanager1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +use doubleclickbidmanager1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use doubleclickbidmanager1::DoubleClickBidManager; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.queries().getquery("queryId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **doubleclickbidmanager1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/doubleclickbidmanager1/src/cmn.rs b/gen/doubleclickbidmanager1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/doubleclickbidmanager1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/doubleclickbidmanager1/src/lib.rs b/gen/doubleclickbidmanager1/src/lib.rs new file mode 100644 index 0000000000..fe1333138b --- /dev/null +++ b/gen/doubleclickbidmanager1/src/lib.rs @@ -0,0 +1,2599 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.0+20150122*, where *20150122* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *DoubleClick Bid Manager* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/bid-manager/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/doubleclickbidmanager1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.DoubleClickBidManager.html) ... +//! +//! * lineitems +//! * [*downloadlineitems*](struct.LineitemDownloadlineitemCall.html) and [*uploadlineitems*](struct.LineitemUploadlineitemCall.html) +//! * [queries](struct.Query.html) +//! * [*createquery*](struct.QueryCreatequeryCall.html), [*deletequery*](struct.QueryDeletequeryCall.html), [*getquery*](struct.QueryGetqueryCall.html), [*listqueries*](struct.QueryListqueryCall.html) and [*runquery*](struct.QueryRunqueryCall.html) +//! * [reports](struct.Report.html) +//! * [*listreports*](struct.ReportListreportCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.DoubleClickBidManager.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.queries().getquery(...).doit() +//! let r = hub.queries().createquery(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-doubleclickbidmanager1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +//! use doubleclickbidmanager1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use doubleclickbidmanager1::DoubleClickBidManager; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.queries().getquery("queryId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all DoubleClickBidManager related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// use doubleclickbidmanager1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().getquery("queryId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct DoubleClickBidManager { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for DoubleClickBidManager {} + +impl<'a, C, NC, A> DoubleClickBidManager + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> DoubleClickBidManager { + DoubleClickBidManager { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn lineitems(&'a self) -> LineitemMethods<'a, C, NC, A> { + LineitemMethods { hub: &self } + } + pub fn queries(&'a self) -> QueryMethods<'a, C, NC, A> { + QueryMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, NC, A> { + ReportMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// Request to fetch stored line items. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [downloadlineitems lineitems](struct.LineitemDownloadlineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct DownloadLineItemsRequest { + /// Filter type used to filter line items to fetch. + #[serde(alias="filterType")] + pub filter_type: Option, + /// Ids of the specified filter type used to filter line items to fetch. If omitted, all the line items will be returned. + #[serde(alias="filterIds")] + pub filter_ids: Option>, + /// Format in which the line items will be returned. Default to CSV. + pub format: Option, +} + +impl RequestValue for DownloadLineItemsRequest {} + + +/// An explanation of a report failure. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportFailure { + /// Error code that shows why the report was not created. + #[serde(alias="errorCode")] + pub error_code: String, +} + +impl Part for ReportFailure {} + + +/// Parameters of a query or report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Parameters { + /// Metrics to include as columns in your report. + pub metrics: Vec, + /// Filters used to match traffic data in your report. + pub filters: Vec, + /// Report type. + #[serde(alias="type")] + pub type_: String, + /// Data is grouped by the filters listed in this field. + #[serde(alias="groupBys")] + pub group_bys: Vec, + /// Whether to include data from Invite Media. + #[serde(alias="includeInviteData")] + pub include_invite_data: bool, +} + +impl Part for Parameters {} + + +/// Key used to identify a report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportKey { + /// Query ID. + #[serde(alias="queryId")] + pub query_id: String, + /// Report ID. + #[serde(alias="reportId")] + pub report_id: String, +} + +impl Part for ReportKey {} + + +/// Request to upload line items. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [uploadlineitems lineitems](struct.LineitemUploadlineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UploadLineItemsRequest { + /// Line items in CSV to upload. Refer to Entity Write File Format for more information on file format. + #[serde(alias="lineItems")] + pub line_items: Option, + /// Set to true to get upload status without actually persisting the line items. + #[serde(alias="dryRun")] + pub dry_run: Option, + /// Format the line items are in. Default to CSV. + pub format: Option, +} + +impl RequestValue for UploadLineItemsRequest {} + + +/// List queries response. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [listqueries queries](struct.QueryListqueryCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListQueriesResponse { + /// Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#listQueriesResponse". + pub kind: String, + /// Retrieved queries. + pub queries: Vec, +} + +impl ResponseResult for ListQueriesResponse {} + + +/// Report metadata. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportMetadata { + /// Report status. + pub status: ReportStatus, + /// The ending time for the data that is shown in the report. + #[serde(alias="reportDataEndTimeMs")] + pub report_data_end_time_ms: String, + /// The path to the location in Google Cloud Storage where the report is stored. + #[serde(alias="googleCloudStoragePath")] + pub google_cloud_storage_path: String, + /// The starting time for the data that is shown in the report. + #[serde(alias="reportDataStartTimeMs")] + pub report_data_start_time_ms: String, +} + +impl Part for ReportMetadata {} + + +/// Information on how frequently and when to run a query. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct QuerySchedule { + /// Datetime to periodically run the query until. + #[serde(alias="endTimeMs")] + pub end_time_ms: String, + /// How often the query is run. + pub frequency: String, + /// Time of day at which a new report will be generated, represented as minutes past midnight. Range is 0 to 1439. Only applies to scheduled reports. + #[serde(alias="nextRunMinuteOfDay")] + pub next_run_minute_of_day: i32, + /// Canonical timezone code for report generation time. Defaults to America/New_York. + #[serde(alias="nextRunTimezoneCode")] + pub next_run_timezone_code: String, +} + +impl Part for QuerySchedule {} + + +/// Request to run a stored query to generate a report. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [runquery queries](struct.QueryRunqueryCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct RunQueryRequest { + /// The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if dataRange is CUSTOM_DATES and ignored otherwise. + #[serde(alias="reportDataEndTimeMs")] + pub report_data_end_time_ms: Option, + /// Canonical timezone code for report data time. Defaults to America/New_York. + #[serde(alias="timezoneCode")] + pub timezone_code: Option, + /// The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if dataRange is CUSTOM_DATES and ignored otherwise. + #[serde(alias="reportDataStartTimeMs")] + pub report_data_start_time_ms: Option, + /// Report data range used to generate the report. + #[serde(alias="dataRange")] + pub data_range: Option, +} + +impl RequestValue for RunQueryRequest {} + + +/// Upload line items response. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [uploadlineitems lineitems](struct.LineitemUploadlineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UploadLineItemsResponse { + /// Status of upload. + #[serde(alias="uploadStatus")] + pub upload_status: UploadStatus, +} + +impl ResponseResult for UploadLineItemsResponse {} + + +/// Query metadata. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct QueryMetadata { + /// The path to the location in Google Cloud Storage where the latest report is stored. + #[serde(alias="googleCloudStoragePathForLatestReport")] + pub google_cloud_storage_path_for_latest_report: String, + /// Range of report data. + #[serde(alias="dataRange")] + pub data_range: String, + /// Whether to send an email notification when a report is ready. Default to false. + #[serde(alias="sendNotification")] + pub send_notification: bool, + /// Locale of the generated reports. Valid values are cs CZECH de GERMAN en ENGLISH es SPANISH fr FRENCH it ITALIAN ja JAPANESE ko KOREAN pl POLISH pt-BR BRAZILIAN_PORTUGUESE ru RUSSIAN tr TURKISH uk UKRAINIAN zh-CN CHINA_CHINESE zh-TW TAIWAN_CHINESE + /// + /// An locale string not in the list above will generate reports in English. + pub locale: String, + /// The path in Google Drive for the latest report. + #[serde(alias="googleDrivePathForLatestReport")] + pub google_drive_path_for_latest_report: String, + /// Format of the generated report. + pub format: String, + /// List of email addresses which are sent email notifications when the report is finished. Separate from sendNotification. + #[serde(alias="shareEmailAddress")] + pub share_email_address: Vec, + /// Number of reports that have been generated for the query. + #[serde(alias="reportCount")] + pub report_count: i32, + /// Whether the latest report is currently running. + pub running: bool, + /// The time when the latest report started to run. + #[serde(alias="latestReportRunTimeMs")] + pub latest_report_run_time_ms: String, + /// Query title. It is used to name the reports generated from this query. + pub title: String, +} + +impl Part for QueryMetadata {} + + +/// Report status. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportStatus { + /// If the report failed, this records the cause. + pub failure: ReportFailure, + /// The state of the report. + pub state: String, + /// The time when this report either completed successfully or failed. + #[serde(alias="finishTimeMs")] + pub finish_time_ms: String, + /// The file type of the report. + pub format: String, +} + +impl Part for ReportStatus {} + + +/// List reports response. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [listreports reports](struct.ReportListreportCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListReportsResponse { + /// Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#listReportsResponse". + pub kind: String, + /// Retrieved reports. + pub reports: Vec, +} + +impl ResponseResult for ListReportsResponse {} + + +/// Represents the upload status of a row in the request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RowStatus { + /// Whether the entity is persisted. + pub persisted: bool, + /// Reasons why the entity can't be uploaded. + pub errors: Vec, + /// Entity name. + #[serde(alias="entityName")] + pub entity_name: String, + /// Whether the stored entity is changed as a result of upload. + pub changed: bool, + /// Entity Id. + #[serde(alias="entityId")] + pub entity_id: String, + /// Row number. + #[serde(alias="rowNumber")] + pub row_number: i32, +} + +impl Part for RowStatus {} + + +/// Represents a report. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [listreports reports](struct.ReportListreportCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Report { + /// Report parameters. + pub params: Option, + /// Key used to identify a report. + pub key: Option, + /// Report metadata. + pub metadata: Option, +} + +impl Resource for Report {} + + +/// Represents a query. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [getquery queries](struct.QueryGetqueryCall.html) (response) +/// * [createquery queries](struct.QueryCreatequeryCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Query { + /// Identifies what kind of resource this is. Value: the fixed string "doubleclickbidmanager#query". + pub kind: Option, + /// Information on how often and when to run a query. + pub schedule: Option, + /// Canonical timezone code for report data time. Defaults to America/New_York. + #[serde(alias="timezoneCode")] + pub timezone_code: Option, + /// The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if metadata.dataRange is CUSTOM_DATES and ignored otherwise. + #[serde(alias="reportDataEndTimeMs")] + pub report_data_end_time_ms: Option, + /// Query ID. + #[serde(alias="queryId")] + pub query_id: Option, + /// Query parameters. + pub params: Option, + /// The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required if metadata.dataRange is CUSTOM_DATES and ignored otherwise. + #[serde(alias="reportDataStartTimeMs")] + pub report_data_start_time_ms: Option, + /// Query metadata. + pub metadata: Option, +} + +impl RequestValue for Query {} +impl ResponseResult for Query {} + + +/// Download line items response. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [downloadlineitems lineitems](struct.LineitemDownloadlineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct DownloadLineItemsResponse { + /// Retrieved line items in CSV format. Refer to Entity Write File Format for more information on file format. + #[serde(alias="lineItems")] + pub line_items: String, +} + +impl ResponseResult for DownloadLineItemsResponse {} + + +/// Filter used to match traffic data in your report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FilterPair { + /// Filter type. + #[serde(alias="type")] + pub type_: String, + /// Filter value. + pub value: String, +} + +impl Part for FilterPair {} + + +/// Represents the status of upload. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UploadStatus { + /// Reasons why upload can't be completed. + pub errors: Vec, + /// Per-row upload status. + #[serde(alias="rowStatus")] + pub row_status: Vec, +} + +impl Part for UploadStatus {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *lineitem* resources. +/// It is not used directly, but through the `DoubleClickBidManager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `downloadlineitems(...)` and `uploadlineitems(...)` +/// // to build up your call. +/// let rb = hub.lineitems(); +/// # } +/// ``` +pub struct LineitemMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for LineitemMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> LineitemMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Uploads line items in CSV format. + pub fn uploadlineitems(&self, request: &UploadLineItemsRequest) -> LineitemUploadlineitemCall<'a, C, NC, A> { + LineitemUploadlineitemCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves line items in CSV format. + pub fn downloadlineitems(&self, request: &DownloadLineItemsRequest) -> LineitemDownloadlineitemCall<'a, C, NC, A> { + LineitemDownloadlineitemCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *report* resources. +/// It is not used directly, but through the `DoubleClickBidManager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `listreports(...)` +/// // to build up your call. +/// let rb = hub.reports(); +/// # } +/// ``` +pub struct ReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves stored reports. + pub fn listreports(&self, query_id: &str) -> ReportListreportCall<'a, C, NC, A> { + ReportListreportCall { + hub: self.hub, + _query_id: query_id.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *query* resources. +/// It is not used directly, but through the `DoubleClickBidManager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `createquery(...)`, `deletequery(...)`, `getquery(...)`, `listqueries(...)` and `runquery(...)` +/// // to build up your call. +/// let rb = hub.queries(); +/// # } +/// ``` +pub struct QueryMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for QueryMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves stored queries. + pub fn listqueries(&self) -> QueryListqueryCall<'a, C, NC, A> { + QueryListqueryCall { + hub: self.hub, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a stored query. + pub fn getquery(&self, query_id: &str) -> QueryGetqueryCall<'a, C, NC, A> { + QueryGetqueryCall { + hub: self.hub, + _query_id: query_id.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a query. + pub fn createquery(&self, request: &Query) -> QueryCreatequeryCall<'a, C, NC, A> { + QueryCreatequeryCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a stored query as well as the associated stored reports. + pub fn deletequery(&self, query_id: &str) -> QueryDeletequeryCall<'a, C, NC, A> { + QueryDeletequeryCall { + hub: self.hub, + _query_id: query_id.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Runs a stored query to generate a report. + pub fn runquery(&self, request: &RunQueryRequest, query_id: &str) -> QueryRunqueryCall<'a, C, NC, A> { + QueryRunqueryCall { + hub: self.hub, + _request: request.clone(), + _query_id: query_id.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Uploads line items in CSV format. +/// +/// A builder for the *uploadlineitems* method supported by a *lineitem* resource. +/// It is not used directly, but through a `LineitemMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// use doubleclickbidmanager1::UploadLineItemsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UploadLineItemsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.lineitems().uploadlineitems(&req) +/// .doit(); +/// # } +/// ``` +pub struct LineitemUploadlineitemCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _request: UploadLineItemsRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for LineitemUploadlineitemCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LineitemUploadlineitemCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UploadLineItemsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.lineitems.uploadlineitems", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/uploadlineitems".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UploadLineItemsRequest) -> LineitemUploadlineitemCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LineitemUploadlineitemCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LineitemUploadlineitemCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Retrieves line items in CSV format. +/// +/// A builder for the *downloadlineitems* method supported by a *lineitem* resource. +/// It is not used directly, but through a `LineitemMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// use doubleclickbidmanager1::DownloadLineItemsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DownloadLineItemsRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.lineitems().downloadlineitems(&req) +/// .doit(); +/// # } +/// ``` +pub struct LineitemDownloadlineitemCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _request: DownloadLineItemsRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for LineitemDownloadlineitemCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> LineitemDownloadlineitemCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DownloadLineItemsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.lineitems.downloadlineitems", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/downloadlineitems".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DownloadLineItemsRequest) -> LineitemDownloadlineitemCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LineitemDownloadlineitemCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LineitemDownloadlineitemCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Retrieves stored reports. +/// +/// A builder for the *listreports* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().listreports("queryId") +/// .doit(); +/// # } +/// ``` +pub struct ReportListreportCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _query_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for ReportListreportCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportListreportCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListReportsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.reports.listreports", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("queryId", self._query_id.to_string())); + for &field in ["alt", "queryId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/queries/{queryId}/reports".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + for &(find_this, param_name) in [("{queryId}", "queryId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["queryId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *query id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query ID with which the reports are associated. + pub fn query_id(mut self, new_value: &str) -> ReportListreportCall<'a, C, NC, A> { + self._query_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportListreportCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportListreportCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Retrieves stored queries. +/// +/// A builder for the *listqueries* method supported by a *query* resource. +/// It is not used directly, but through a `QueryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().listqueries() +/// .doit(); +/// # } +/// ``` +pub struct QueryListqueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for QueryListqueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryListqueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListQueriesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.queries.listqueries", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/queries".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> QueryListqueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> QueryListqueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Retrieves a stored query. +/// +/// A builder for the *getquery* method supported by a *query* resource. +/// It is not used directly, but through a `QueryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().getquery("queryId") +/// .doit(); +/// # } +/// ``` +pub struct QueryGetqueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _query_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for QueryGetqueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryGetqueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Query)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.queries.getquery", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("queryId", self._query_id.to_string())); + for &field in ["alt", "queryId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + for &(find_this, param_name) in [("{queryId}", "queryId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["queryId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *query id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query ID to retrieve. + pub fn query_id(mut self, new_value: &str) -> QueryGetqueryCall<'a, C, NC, A> { + self._query_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> QueryGetqueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> QueryGetqueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Creates a query. +/// +/// A builder for the *createquery* method supported by a *query* resource. +/// It is not used directly, but through a `QueryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// use doubleclickbidmanager1::Query; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Query = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().createquery(&req) +/// .doit(); +/// # } +/// ``` +pub struct QueryCreatequeryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _request: Query, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for QueryCreatequeryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryCreatequeryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Query)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.queries.createquery", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/query".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Query) -> QueryCreatequeryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> QueryCreatequeryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> QueryCreatequeryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Deletes a stored query as well as the associated stored reports. +/// +/// A builder for the *deletequery* method supported by a *query* resource. +/// It is not used directly, but through a `QueryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().deletequery("queryId") +/// .doit(); +/// # } +/// ``` +pub struct QueryDeletequeryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _query_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for QueryDeletequeryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryDeletequeryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.queries.deletequery", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("queryId", self._query_id.to_string())); + for &field in ["queryId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + for &(find_this, param_name) in [("{queryId}", "queryId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["queryId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *query id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query ID to delete. + pub fn query_id(mut self, new_value: &str) -> QueryDeletequeryCall<'a, C, NC, A> { + self._query_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> QueryDeletequeryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> QueryDeletequeryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Runs a stored query to generate a report. +/// +/// A builder for the *runquery* method supported by a *query* resource. +/// It is not used directly, but through a `QueryMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclickbidmanager1" as doubleclickbidmanager1; +/// use doubleclickbidmanager1::RunQueryRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclickbidmanager1::DoubleClickBidManager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = DoubleClickBidManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: RunQueryRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.queries().runquery(&req, "queryId") +/// .doit(); +/// # } +/// ``` +pub struct QueryRunqueryCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a DoubleClickBidManager, + _request: RunQueryRequest, + _query_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for QueryRunqueryCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> QueryRunqueryCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclickbidmanager.queries.runquery", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("queryId", self._query_id.to_string())); + for &field in ["queryId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/doubleclickbidmanager/v1/query/{queryId}".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + for &(find_this, param_name) in [("{queryId}", "queryId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["queryId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &RunQueryRequest) -> QueryRunqueryCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *query id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Query ID to run. + pub fn query_id(mut self, new_value: &str) -> QueryRunqueryCall<'a, C, NC, A> { + self._query_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> QueryRunqueryCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> QueryRunqueryCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + diff --git a/gen/doubleclicksearch2/Cargo.toml b/gen/doubleclicksearch2/Cargo.toml new file mode 100644 index 0000000000..5142ca2173 --- /dev/null +++ b/gen/doubleclicksearch2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-doubleclicksearch2" +version = "0.1.0+20150224" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with doubleclicksearch (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/doubleclicksearch2" +homepage = "https://developers.google.com/doubleclick-search/" +documentation = "http://byron.github.io/google-apis-rs/google-doubleclicksearch2" +license = "MIT" +keywords = ["doubleclicksearch", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/doubleclicksearch2/LICENSE.md b/gen/doubleclicksearch2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/doubleclicksearch2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/doubleclicksearch2/README.md b/gen/doubleclicksearch2/README.md new file mode 100644 index 0000000000..60ec79277e --- /dev/null +++ b/gen/doubleclicksearch2/README.md @@ -0,0 +1,174 @@ + +The `google-doubleclicksearch2` library allows access to all features of the *Google doubleclicksearch* service. + +This documentation was generated from *doubleclicksearch* crate version *0.1.0+20150224*, where *20150224* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *doubleclicksearch* *v2* API can be found at the +[official documentation site](https://developers.google.com/doubleclick-search/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.Doubleclicksearch.html) ... + +* [conversion](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.Conversion.html) + * [*get*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ConversionGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ConversionInsertCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ConversionPatchCall.html), [*update*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ConversionUpdateCall.html) and [*update availability*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ConversionUpdateAvailabilityCall.html) +* [reports](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.Report.html) + * [*generate*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ReportGenerateCall.html), [*get*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ReportGetCall.html), [*get file*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ReportGetFileCall.html) and [*request*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ReportRequestCall.html) +* [saved columns](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.SavedColumn.html) + * [*list*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.SavedColumnListCall.html) + + +Download supported by ... + +* [*get file reports*](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.ReportGetFileCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/struct.Doubleclicksearch.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.reports().generate(...).doit() +let r = hub.reports().get_file(...).doit() +let r = hub.reports().get(...).doit() +let r = hub.reports().request(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-doubleclicksearch2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-doubleclicksearch2" as doubleclicksearch2; +use doubleclicksearch2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use doubleclicksearch2::Doubleclicksearch; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.reports().get_file("reportId", -48) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-doubleclicksearch2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **doubleclicksearch2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/doubleclicksearch2/src/cmn.rs b/gen/doubleclicksearch2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/doubleclicksearch2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/doubleclicksearch2/src/lib.rs b/gen/doubleclicksearch2/src/lib.rs new file mode 100644 index 0000000000..a928a5b422 --- /dev/null +++ b/gen/doubleclicksearch2/src/lib.rs @@ -0,0 +1,3590 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *doubleclicksearch* crate version *0.1.0+20150224*, where *20150224* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *doubleclicksearch* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/doubleclick-search/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/doubleclicksearch2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Doubleclicksearch.html) ... +//! +//! * [conversion](struct.Conversion.html) +//! * [*get*](struct.ConversionGetCall.html), [*insert*](struct.ConversionInsertCall.html), [*patch*](struct.ConversionPatchCall.html), [*update*](struct.ConversionUpdateCall.html) and [*update availability*](struct.ConversionUpdateAvailabilityCall.html) +//! * [reports](struct.Report.html) +//! * [*generate*](struct.ReportGenerateCall.html), [*get*](struct.ReportGetCall.html), [*get file*](struct.ReportGetFileCall.html) and [*request*](struct.ReportRequestCall.html) +//! * [saved columns](struct.SavedColumn.html) +//! * [*list*](struct.SavedColumnListCall.html) +//! +//! +//! Download supported by ... +//! +//! * [*get file reports*](struct.ReportGetFileCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Doubleclicksearch.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.reports().generate(...).doit() +//! let r = hub.reports().get_file(...).doit() +//! let r = hub.reports().get(...).doit() +//! let r = hub.reports().request(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-doubleclicksearch2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-doubleclicksearch2" as doubleclicksearch2; +//! use doubleclicksearch2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use doubleclicksearch2::Doubleclicksearch; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.reports().get_file("reportId", -42) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage your advertising data in DoubleClick Search + Full, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/doubleclicksearch", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Doubleclicksearch related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclicksearch2::Doubleclicksearch; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().get_file("reportId", -18) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Doubleclicksearch { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Doubleclicksearch {} + +impl<'a, C, NC, A> Doubleclicksearch + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Doubleclicksearch { + Doubleclicksearch { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn conversion(&'a self) -> ConversionMethods<'a, C, NC, A> { + ConversionMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, NC, A> { + ReportMethods { hub: &self } + } + pub fn saved_columns(&'a self) -> SavedColumnMethods<'a, C, NC, A> { + SavedColumnMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A message containing the custome dimension. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomDimension { + /// Custom dimension name. + pub name: String, + /// Custom dimension value. + pub value: String, +} + +impl Part for CustomDimension {} + + +/// A message containing the custome metric. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomMetric { + /// Custom metric name. + pub name: String, + /// Custom metric numeric value. + pub value: f64, +} + +impl Part for CustomMetric {} + + +/// A conversion containing data relevant to DoubleClick Search. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Conversion { + /// Custom dimensions for the conversion, which can be used to filter data in a report. + #[serde(alias="customDimension")] + pub custom_dimension: Vec, + /// DS ad group ID. + #[serde(alias="adGroupId")] + pub ad_group_id: String, + /// The numeric segmentation identifier (for example, DoubleClick Search Floodlight activity ID). + #[serde(alias="segmentationId")] + pub segmentation_id: String, + /// Attribution model name. + #[serde(alias="attributionModel")] + pub attribution_model: String, + /// DS campaign ID. + #[serde(alias="campaignId")] + pub campaign_id: String, + /// The revenue amount of this TRANSACTION conversion, in micros. + #[serde(alias="revenueMicros")] + pub revenue_micros: String, + /// DS advertiser ID. + #[serde(alias="advertiserId")] + pub advertiser_id: String, + /// The quantity of this conversion, in millis. + #[serde(alias="quantityMillis")] + pub quantity_millis: String, + /// Conversion count in millis. + #[serde(alias="countMillis")] + pub count_millis: String, + /// DS criterion (keyword) ID. + #[serde(alias="criterionId")] + pub criterion_id: String, + /// The time at which the conversion took place, in epoch millis UTC. + #[serde(alias="conversionTimestamp")] + pub conversion_timestamp: String, + /// The advertiser-provided order id for the conversion. + #[serde(alias="floodlightOrderId")] + pub floodlight_order_id: String, + /// The segmentation type of this conversion (for example, FLOODLIGHT). + #[serde(alias="segmentationType")] + pub segmentation_type: String, + /// DS click ID for the conversion. + #[serde(alias="clickId")] + pub click_id: String, + /// Custom metrics for the conversion. + #[serde(alias="customMetric")] + pub custom_metric: Vec, + /// DS conversion ID. + #[serde(alias="dsConversionId")] + pub ds_conversion_id: String, + /// DS engine account ID. + #[serde(alias="engineAccountId")] + pub engine_account_id: String, + /// The time at which the conversion was last modified, in epoch millis UTC. + #[serde(alias="conversionModifiedTimestamp")] + pub conversion_modified_timestamp: String, + /// The currency code for the conversion's revenue. Should be in ISO 4217 alphabetic (3-char) format. + #[serde(alias="currencyCode")] + pub currency_code: String, + /// The friendly segmentation identifier (for example, DoubleClick Search Floodlight activity name). + #[serde(alias="segmentationName")] + pub segmentation_name: String, + /// The state of the conversion, that is, either ACTIVE or REMOVED. Note: state DELETED is deprecated. + pub state: String, + /// DS ad ID. + #[serde(alias="adId")] + pub ad_id: String, + /// DS agency ID. + #[serde(alias="agencyId")] + pub agency_id: String, + /// Advertiser-provided ID for the conversion, also known as the order ID. + #[serde(alias="conversionId")] + pub conversion_id: String, + /// The type of the conversion, that is, either ACTION or TRANSACTION. An ACTION conversion is an action by the user that has no monetarily quantifiable value, while a TRANSACTION conversion is an action that does have a monetarily quantifiable value. Examples are email list signups (ACTION) versus ecommerce purchases (TRANSACTION). + #[serde(alias="type")] + pub type_: String, +} + +impl Part for Conversion {} + + +/// A row in a DoubleClick Search report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportRow(HashMap); + +impl Part for ReportRow {} + + +/// Asynchronous report only. Contains a list of generated report files once the report has succesfully completed. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReportFiles { + /// Use this url to download the report file. + pub url: String, + /// The size of this report file in bytes. + #[serde(alias="byteCount")] + pub byte_count: i64, +} + +impl NestedType for ReportFiles {} +impl Part for ReportFiles {} + + +/// The reportScope is a set of IDs that are used to determine which subset of entities will be returned in the report. The full lineage of IDs from the lowest scoped level desired up through agency is required. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportRequestReportScope { + /// DS advertiser ID. + #[serde(alias="advertiserId")] + pub advertiser_id: String, + /// DS ad group ID. + #[serde(alias="adGroupId")] + pub ad_group_id: String, + /// DS keyword ID. + #[serde(alias="keywordId")] + pub keyword_id: String, + /// DS ad ID. + #[serde(alias="adId")] + pub ad_id: String, + /// DS agency ID. + #[serde(alias="agencyId")] + pub agency_id: String, + /// DS engine account ID. + #[serde(alias="engineAccountId")] + pub engine_account_id: String, + /// DS campaign ID. + #[serde(alias="campaignId")] + pub campaign_id: String, +} + +impl NestedType for ReportRequestReportScope {} +impl Part for ReportRequestReportScope {} + + +/// A list of filters to be applied to the report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportRequestFilters { + /// Column to perform the filter on. This can be a DoubleClick Search column or a saved column. + pub column: ReportApiColumnSpec, + /// Operator to use in the filter. See the filter reference for a list of available operators. + pub operator: String, + /// A list of values to filter the column value against. + pub values: Vec, +} + +impl NestedType for ReportRequestFilters {} +impl Part for ReportRequestFilters {} + + +/// Synchronous report only. A list of columns and directions defining sorting to be performed on the report rows. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportRequestOrderBy { + /// Column to perform the sort on. This can be a DoubleClick Search-defined column or a saved column. + pub column: ReportApiColumnSpec, + /// The sort direction, which is either ascending or descending. + #[serde(alias="sortOrder")] + pub sort_order: String, +} + +impl NestedType for ReportRequestOrderBy {} +impl Part for ReportRequestOrderBy {} + + +/// A request object used to create a DoubleClick Search report. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportApiColumnSpec { + /// Synchronous report only. Set to true to group by this column. Defaults to false. + #[serde(alias="groupByColumn")] + pub group_by_column: bool, + /// Inclusive day in YYYY-MM-DD format. When provided, this overrides the overall time range of the report for this column only. Must be provided together with startDate. + #[serde(alias="endDate")] + pub end_date: String, + /// Name of a saved column to include in the report. The report must be scoped at advertiser or lower, and this saved column must already be created in the DoubleClick Search UI. + #[serde(alias="savedColumnName")] + pub saved_column_name: String, + /// Segments a report by a custom dimension. The report must be scoped to an advertiser or lower, and the custom dimension must already be set up in DoubleClick Search. The custom dimension name, which appears in DoubleClick Search, is case sensitive. + /// If used in a conversion report, returns the value of the specified custom dimension for the given conversion, if set. This column does not segment the conversion report. + #[serde(alias="customDimensionName")] + pub custom_dimension_name: String, + /// Text used to identify this column in the report output; defaults to columnName or savedColumnName when not specified. This can be used to prevent collisions between DoubleClick Search columns and saved columns with the same name. + #[serde(alias="headerText")] + pub header_text: String, + /// Name of a DoubleClick Search column to include in the report. + #[serde(alias="columnName")] + pub column_name: String, + /// The platform that is used to provide data for the custom dimension. Acceptable values are "Floodlight". + #[serde(alias="platformSource")] + pub platform_source: String, + /// Inclusive date in YYYY-MM-DD format. When provided, this overrides the overall time range of the report for this column only. Must be provided together with endDate. + #[serde(alias="startDate")] + pub start_date: String, + /// Name of a custom metric to include in the report. The report must be scoped to an advertiser or lower, and the custom metric must already be set up in DoubleClick Search. The custom metric name, which appears in DoubleClick Search, is case sensitive. + #[serde(alias="customMetricName")] + pub custom_metric_name: String, +} + +impl Part for ReportApiColumnSpec {} + + +/// A message containing availability data relevant to DoubleClick Search. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Availability { + /// DS advertiser ID. + #[serde(alias="advertiserId")] + pub advertiser_id: String, + /// The numeric segmentation identifier (for example, DoubleClick Search Floodlight activity ID). + #[serde(alias="segmentationId")] + pub segmentation_id: String, + /// The segmentation type that this availability is for (its default value is FLOODLIGHT). + #[serde(alias="segmentationType")] + pub segmentation_type: String, + /// DS agency ID. + #[serde(alias="agencyId")] + pub agency_id: String, + /// The friendly segmentation identifier (for example, DoubleClick Search Floodlight activity name). + #[serde(alias="segmentationName")] + pub segmentation_name: String, + /// The time by which all conversions have been uploaded, in epoch millis UTC. + #[serde(alias="availabilityTimestamp")] + pub availability_timestamp: String, +} + +impl Part for Availability {} + + +/// A request object used to create a DoubleClick Search report. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generate reports](struct.ReportGenerateCall.html) (request) +/// * [request reports](struct.ReportRequestCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportRequest { + /// Synchronous report only. A list of columns and directions defining sorting to be performed on the report rows. + #[serde(alias="orderBy")] + pub order_by: Option>, + /// The reportScope is a set of IDs that are used to determine which subset of entities will be returned in the report. The full lineage of IDs from the lowest scoped level desired up through agency is required. + #[serde(alias="reportScope")] + pub report_scope: Option, + /// Asynchronous report only. The maximum number of rows per report file. A large report is split into many files based on this field. Acceptable values are 1000000 to 100000000, inclusive. + #[serde(alias="maxRowsPerFile")] + pub max_rows_per_file: Option, + /// Specifies the currency in which monetary will be returned. Possible values are: usd, agency (valid if the report is scoped to agency or lower), advertiser (valid if the report is scoped to * advertiser or lower), or account (valid if the report is scoped to engine account or lower). + #[serde(alias="statisticsCurrency")] + pub statistics_currency: Option, + /// If metrics are requested in a report, this argument will be used to restrict the metrics to a specific time range. + #[serde(alias="timeRange")] + pub time_range: Option, + /// Synchronous report only. Zero-based index of the first row to return. Acceptable values are 0 to 50000, inclusive. Defaults to 0. + #[serde(alias="startRow")] + pub start_row: Option, + /// Synchronous report only. The maxinum number of rows to return; additional rows are dropped. Acceptable values are 0 to 10000, inclusive. Defaults to 10000. + #[serde(alias="rowCount")] + pub row_count: Option, + /// Determines the type of rows that are returned in the report. For example, if you specify reportType: keyword, each row in the report will contain data about a keyword. See the Types of Reports reference for the columns that are available for each type. + #[serde(alias="reportType")] + pub report_type: Option, + /// The columns to include in the report. This includes both DoubleClick Search columns and saved columns. For DoubleClick Search columns, only the columnName parameter is required. For saved columns only the savedColumnName parameter is required. Both columnName and savedColumnName cannot be set in the same stanza. + pub columns: Option>, + /// A list of filters to be applied to the report. + pub filters: Option>, + /// Determines if removed entities should be included in the report. Defaults to false. + #[serde(alias="includeRemovedEntities")] + pub include_removed_entities: Option, + /// Determines if removed entities should be included in the report. Defaults to false. Deprecated, please use includeRemovedEntities instead. + #[serde(alias="includeDeletedEntities")] + pub include_deleted_entities: Option, + /// If true, the report would only be created if all the requested stat data are sourced from a single timezone. Defaults to false. + #[serde(alias="verifySingleTimeZone")] + pub verify_single_time_zone: Option, + /// Format that the report should be returned in. Currently csv or tsv is supported. + #[serde(alias="downloadFormat")] + pub download_format: Option, +} + +impl RequestValue for ReportRequest {} + + +/// A DoubleClick Search report. This object contains the report request, some report metadata such as currency code, and the generated report rows or report files. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [generate reports](struct.ReportGenerateCall.html) (response) +/// * [get file reports](struct.ReportGetFileCall.html) (none) +/// * [get reports](struct.ReportGetCall.html) (response) +/// * [request reports](struct.ReportRequestCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Report { + /// Asynchronous report only. Contains a list of generated report files once the report has succesfully completed. + pub files: Vec, + /// Identifies this as a Report resource. Value: the fixed string doubleclicksearch#report. + pub kind: String, + /// Synchronous report only. Generated report rows. + pub rows: Vec, + /// The request that created the report. Optional fields not specified in the original request are filled with default values. + pub request: ReportRequest, + /// Asynchronous report only. True if and only if the report has completed successfully and the report files are ready to be downloaded. + #[serde(alias="isReportReady")] + pub is_report_ready: bool, + /// The number of report rows generated by the report, not including headers. + #[serde(alias="rowCount")] + pub row_count: i32, + /// If all statistics of the report are sourced from the same time zone, this would be it. Otherwise the field is unset. + #[serde(alias="statisticsTimeZone")] + pub statistics_time_zone: String, + /// The currency code of all monetary values produced in the report, including values that are set by users (e.g., keyword bid settings) and metrics (e.g., cost and revenue). The currency code of a report is determined by the statisticsCurrency field of the report request. + #[serde(alias="statisticsCurrencyCode")] + pub statistics_currency_code: String, + /// Asynchronous report only. Id of the report. + pub id: String, +} + +impl Resource for Report {} +impl ResponseResult for Report {} + + +/// If metrics are requested in a report, this argument will be used to restrict the metrics to a specific time range. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportRequestTimeRange { + /// Inclusive UTC timestamp in RFC format, e.g., 2013-07-16T10:16:23.555Z. See additional references on how changed metrics reports work. + #[serde(alias="changedMetricsSinceTimestamp")] + pub changed_metrics_since_timestamp: String, + /// Inclusive date in YYYY-MM-DD format. + #[serde(alias="endDate")] + pub end_date: String, + /// Inclusive UTC timestamp in RFC format, e.g., 2013-07-16T10:16:23.555Z. See additional references on how changed attribute reports work. + #[serde(alias="changedAttributesSinceTimestamp")] + pub changed_attributes_since_timestamp: String, + /// Inclusive date in YYYY-MM-DD format. + #[serde(alias="startDate")] + pub start_date: String, +} + +impl NestedType for ReportRequestTimeRange {} +impl Part for ReportRequestTimeRange {} + + +/// A list of saved columns. Advertisers create saved columns to report on Floodlight activities, Google Analytics goals, or custom KPIs. To request reports with saved columns, you'll need the saved column names that are available from this list. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list saved columns](struct.SavedColumnListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedColumnList { + /// The saved columns being requested. + pub items: Vec, + /// Identifies this as a SavedColumnList resource. Value: the fixed string doubleclicksearch#savedColumnList. + pub kind: String, +} + +impl ResponseResult for SavedColumnList {} + + +/// A saved column +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list saved columns](struct.SavedColumnListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct SavedColumn { + /// The name of the saved column. + #[serde(alias="savedColumnName")] + pub saved_column_name: Option, + /// Identifies this as a SavedColumn resource. Value: the fixed string doubleclicksearch#savedColumn. + pub kind: Option, + /// The type of data this saved column will produce. + #[serde(alias="type")] + pub type_: Option, +} + +impl Resource for SavedColumn {} + + +/// The request to update availability. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update availability conversion](struct.ConversionUpdateAvailabilityCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize)] +pub struct UpdateAvailabilityRequest { + /// The availabilities being requested. + pub availabilities: Option>, +} + +impl RequestValue for UpdateAvailabilityRequest {} + + +/// The response to a update availability request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update availability conversion](struct.ConversionUpdateAvailabilityCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct UpdateAvailabilityResponse { + /// The availabilities being returned. + pub availabilities: Vec, +} + +impl ResponseResult for UpdateAvailabilityResponse {} + + +/// A list of conversions. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert conversion](struct.ConversionInsertCall.html) (request|response) +/// * [get conversion](struct.ConversionGetCall.html) (response) +/// * [patch conversion](struct.ConversionPatchCall.html) (request|response) +/// * [update conversion](struct.ConversionUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ConversionList { + /// The conversions being requested. + pub conversion: Option>, + /// Identifies this as a ConversionList resource. Value: the fixed string doubleclicksearch#conversionList. + pub kind: Option, +} + +impl RequestValue for ConversionList {} +impl ResponseResult for ConversionList {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *conversion* resources. +/// It is not used directly, but through the `Doubleclicksearch` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclicksearch2::Doubleclicksearch; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `insert(...)`, `patch(...)`, `update(...)` and `update_availability(...)` +/// // to build up your call. +/// let rb = hub.conversion(); +/// # } +/// ``` +pub struct ConversionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ConversionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a batch of new conversions into DoubleClick Search. + pub fn insert(&self, request: &ConversionList) -> ConversionInsertCall<'a, C, NC, A> { + ConversionInsertCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of conversions from a DoubleClick Search engine account. + pub fn get(&self, agency_id: &str, advertiser_id: &str, engine_account_id: &str, end_date: i32, row_count: i32, start_date: i32, start_row: u32) -> ConversionGetCall<'a, C, NC, A> { + ConversionGetCall { + hub: self.hub, + _agency_id: agency_id.to_string(), + _advertiser_id: advertiser_id.to_string(), + _engine_account_id: engine_account_id.to_string(), + _end_date: end_date, + _row_count: row_count, + _start_date: start_date, + _start_row: start_row, + _criterion_id: Default::default(), + _campaign_id: Default::default(), + _ad_id: Default::default(), + _ad_group_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the availabilities of a batch of floodlight activities in DoubleClick Search. + pub fn update_availability(&self, request: &UpdateAvailabilityRequest) -> ConversionUpdateAvailabilityCall<'a, C, NC, A> { + ConversionUpdateAvailabilityCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a batch of conversions in DoubleClick Search. This method supports patch semantics. + pub fn patch(&self, request: &ConversionList, advertiser_id: &str, agency_id: &str, end_date: i32, engine_account_id: &str, row_count: i32, start_date: i32, start_row: u32) -> ConversionPatchCall<'a, C, NC, A> { + ConversionPatchCall { + hub: self.hub, + _request: request.clone(), + _advertiser_id: advertiser_id.to_string(), + _agency_id: agency_id.to_string(), + _end_date: end_date, + _engine_account_id: engine_account_id.to_string(), + _row_count: row_count, + _start_date: start_date, + _start_row: start_row, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a batch of conversions in DoubleClick Search. + pub fn update(&self, request: &ConversionList) -> ConversionUpdateCall<'a, C, NC, A> { + ConversionUpdateCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *savedColumn* resources. +/// It is not used directly, but through the `Doubleclicksearch` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclicksearch2::Doubleclicksearch; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `list(...)` +/// // to build up your call. +/// let rb = hub.saved_columns(); +/// # } +/// ``` +pub struct SavedColumnMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for SavedColumnMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> SavedColumnMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve the list of saved columns for a specified advertiser. + pub fn list(&self, agency_id: &str, advertiser_id: &str) -> SavedColumnListCall<'a, C, NC, A> { + SavedColumnListCall { + hub: self.hub, + _agency_id: agency_id.to_string(), + _advertiser_id: advertiser_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *report* resources. +/// It is not used directly, but through the `Doubleclicksearch` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use doubleclicksearch2::Doubleclicksearch; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `generate(...)`, `get(...)`, `get_file(...)` and `request(...)` +/// // to build up your call. +/// let rb = hub.reports(); +/// # } +/// ``` +pub struct ReportMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReportMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Downloads a report file. + pub fn get_file(&self, report_id: &str, report_fragment: i32) -> ReportGetFileCall<'a, C, NC, A> { + ReportGetFileCall { + hub: self.hub, + _report_id: report_id.to_string(), + _report_fragment: report_fragment, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Generates and returns a report immediately. + pub fn generate(&self, request: &ReportRequest) -> ReportGenerateCall<'a, C, NC, A> { + ReportGenerateCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Polls for the status of a report request. + pub fn get(&self, report_id: &str) -> ReportGetCall<'a, C, NC, A> { + ReportGetCall { + hub: self.hub, + _report_id: report_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a report request into the reporting system. + pub fn request(&self, request: &ReportRequest) -> ReportRequestCall<'a, C, NC, A> { + ReportRequestCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Inserts a batch of new conversions into DoubleClick Search. +/// +/// A builder for the *insert* method supported by a *conversion* resource. +/// It is not used directly, but through a `ConversionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::ConversionList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ConversionList = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.conversion().insert(&req) +/// .doit(); +/// # } +/// ``` +pub struct ConversionInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: ConversionList, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConversionInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConversionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.conversion.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/conversion".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ConversionList) -> ConversionInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConversionInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConversionInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConversionInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieves a list of conversions from a DoubleClick Search engine account. +/// +/// A builder for the *get* method supported by a *conversion* resource. +/// It is not used directly, but through a `ConversionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.conversion().get("agencyId", "advertiserId", "engineAccountId", -70, -1, -81, 66) +/// .criterion_id("sea") +/// .campaign_id("nonumy") +/// .ad_id("dolores") +/// .ad_group_id("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct ConversionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _agency_id: String, + _advertiser_id: String, + _engine_account_id: String, + _end_date: i32, + _row_count: i32, + _start_date: i32, + _start_row: u32, + _criterion_id: Option, + _campaign_id: Option, + _ad_id: Option, + _ad_group_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConversionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConversionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.conversion.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); + params.push(("agencyId", self._agency_id.to_string())); + params.push(("advertiserId", self._advertiser_id.to_string())); + params.push(("engineAccountId", self._engine_account_id.to_string())); + params.push(("endDate", self._end_date.to_string())); + params.push(("rowCount", self._row_count.to_string())); + params.push(("startDate", self._start_date.to_string())); + params.push(("startRow", self._start_row.to_string())); + if let Some(value) = self._criterion_id { + params.push(("criterionId", value.to_string())); + } + if let Some(value) = self._campaign_id { + params.push(("campaignId", value.to_string())); + } + if let Some(value) = self._ad_id { + params.push(("adId", value.to_string())); + } + if let Some(value) = self._ad_group_id { + params.push(("adGroupId", value.to_string())); + } + for &field in ["alt", "agencyId", "advertiserId", "engineAccountId", "endDate", "rowCount", "startDate", "startRow", "criterionId", "campaignId", "adId", "adGroupId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/agency/{agencyId}/advertiser/{advertiserId}/engine/{engineAccountId}/conversion".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{agencyId}", "agencyId"), ("{advertiserId}", "advertiserId"), ("{engineAccountId}", "engineAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["agencyId", "advertiserId", "engineAccountId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *agency id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the agency. + pub fn agency_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._agency_id = new_value.to_string(); + self + } + /// Sets the *advertiser id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the advertiser. + pub fn advertiser_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Sets the *engine account id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the engine account. + pub fn engine_account_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._engine_account_id = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Last date (inclusive) on which to retrieve conversions. Format is yyyymmdd. + pub fn end_date(mut self, new_value: i32) -> ConversionGetCall<'a, C, NC, A> { + self._end_date = new_value; + self + } + /// Sets the *row count* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The number of conversions to return per call. + pub fn row_count(mut self, new_value: i32) -> ConversionGetCall<'a, C, NC, A> { + self._row_count = new_value; + self + } + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// First date (inclusive) on which to retrieve conversions. Format is yyyymmdd. + pub fn start_date(mut self, new_value: i32) -> ConversionGetCall<'a, C, NC, A> { + self._start_date = new_value; + self + } + /// Sets the *start row* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The 0-based starting index for retrieving conversions results. + pub fn start_row(mut self, new_value: u32) -> ConversionGetCall<'a, C, NC, A> { + self._start_row = new_value; + self + } + /// Sets the *criterion id* query property to the given value. + /// + /// + /// Numeric ID of the criterion. + pub fn criterion_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._criterion_id = Some(new_value.to_string()); + self + } + /// Sets the *campaign id* query property to the given value. + /// + /// + /// Numeric ID of the campaign. + pub fn campaign_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Sets the *ad id* query property to the given value. + /// + /// + /// Numeric ID of the ad. + pub fn ad_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._ad_id = Some(new_value.to_string()); + self + } + /// Sets the *ad group id* query property to the given value. + /// + /// + /// Numeric ID of the ad group. + pub fn ad_group_id(mut self, new_value: &str) -> ConversionGetCall<'a, C, NC, A> { + self._ad_group_id = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConversionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConversionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConversionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates the availabilities of a batch of floodlight activities in DoubleClick Search. +/// +/// A builder for the *updateAvailability* method supported by a *conversion* resource. +/// It is not used directly, but through a `ConversionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::UpdateAvailabilityRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: UpdateAvailabilityRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.conversion().update_availability(&req) +/// .doit(); +/// # } +/// ``` +pub struct ConversionUpdateAvailabilityCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: UpdateAvailabilityRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConversionUpdateAvailabilityCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionUpdateAvailabilityCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UpdateAvailabilityResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.conversion.updateAvailability", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/conversion/updateAvailability".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &UpdateAvailabilityRequest) -> ConversionUpdateAvailabilityCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConversionUpdateAvailabilityCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConversionUpdateAvailabilityCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConversionUpdateAvailabilityCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a batch of conversions in DoubleClick Search. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *conversion* resource. +/// It is not used directly, but through a `ConversionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::ConversionList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ConversionList = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.conversion().patch(&req, "advertiserId", "agencyId", -66, "engineAccountId", -21, -21, 67) +/// .doit(); +/// # } +/// ``` +pub struct ConversionPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: ConversionList, + _advertiser_id: String, + _agency_id: String, + _end_date: i32, + _engine_account_id: String, + _row_count: i32, + _start_date: i32, + _start_row: u32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConversionPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConversionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.conversion.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("advertiserId", self._advertiser_id.to_string())); + params.push(("agencyId", self._agency_id.to_string())); + params.push(("endDate", self._end_date.to_string())); + params.push(("engineAccountId", self._engine_account_id.to_string())); + params.push(("rowCount", self._row_count.to_string())); + params.push(("startDate", self._start_date.to_string())); + params.push(("startRow", self._start_row.to_string())); + for &field in ["alt", "advertiserId", "agencyId", "endDate", "engineAccountId", "rowCount", "startDate", "startRow"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/conversion".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ConversionList) -> ConversionPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *advertiser id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the advertiser. + pub fn advertiser_id(mut self, new_value: &str) -> ConversionPatchCall<'a, C, NC, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Sets the *agency id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the agency. + pub fn agency_id(mut self, new_value: &str) -> ConversionPatchCall<'a, C, NC, A> { + self._agency_id = new_value.to_string(); + self + } + /// Sets the *end date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Last date (inclusive) on which to retrieve conversions. Format is yyyymmdd. + pub fn end_date(mut self, new_value: i32) -> ConversionPatchCall<'a, C, NC, A> { + self._end_date = new_value; + self + } + /// Sets the *engine account id* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Numeric ID of the engine account. + pub fn engine_account_id(mut self, new_value: &str) -> ConversionPatchCall<'a, C, NC, A> { + self._engine_account_id = new_value.to_string(); + self + } + /// Sets the *row count* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The number of conversions to return per call. + pub fn row_count(mut self, new_value: i32) -> ConversionPatchCall<'a, C, NC, A> { + self._row_count = new_value; + self + } + /// Sets the *start date* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// First date (inclusive) on which to retrieve conversions. Format is yyyymmdd. + pub fn start_date(mut self, new_value: i32) -> ConversionPatchCall<'a, C, NC, A> { + self._start_date = new_value; + self + } + /// Sets the *start row* query property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The 0-based starting index for retrieving conversions results. + pub fn start_row(mut self, new_value: u32) -> ConversionPatchCall<'a, C, NC, A> { + self._start_row = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConversionPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConversionPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConversionPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a batch of conversions in DoubleClick Search. +/// +/// A builder for the *update* method supported by a *conversion* resource. +/// It is not used directly, but through a `ConversionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::ConversionList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ConversionList = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.conversion().update(&req) +/// .doit(); +/// # } +/// ``` +pub struct ConversionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: ConversionList, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ConversionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ConversionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConversionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.conversion.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/conversion".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ConversionList) -> ConversionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConversionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConversionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConversionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Retrieve the list of saved columns for a specified advertiser. +/// +/// A builder for the *list* method supported by a *savedColumn* resource. +/// It is not used directly, but through a `SavedColumnMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.saved_columns().list("agencyId", "advertiserId") +/// .doit(); +/// # } +/// ``` +pub struct SavedColumnListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _agency_id: String, + _advertiser_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for SavedColumnListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> SavedColumnListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SavedColumnList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.savedColumns.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("agencyId", self._agency_id.to_string())); + params.push(("advertiserId", self._advertiser_id.to_string())); + for &field in ["alt", "agencyId", "advertiserId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/agency/{agencyId}/advertiser/{advertiserId}/savedcolumns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{agencyId}", "agencyId"), ("{advertiserId}", "advertiserId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["agencyId", "advertiserId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *agency id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// DS ID of the agency. + pub fn agency_id(mut self, new_value: &str) -> SavedColumnListCall<'a, C, NC, A> { + self._agency_id = new_value.to_string(); + self + } + /// Sets the *advertiser id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// DS ID of the advertiser. + pub fn advertiser_id(mut self, new_value: &str) -> SavedColumnListCall<'a, C, NC, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SavedColumnListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SavedColumnListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SavedColumnListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Downloads a report file. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// +/// A builder for the *getFile* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().get_file("reportId", -5) +/// .doit(); +/// # } +/// ``` +pub struct ReportGetFileCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _report_id: String, + _report_fragment: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGetFileCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGetFileCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.reports.getFile", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("reportId", self._report_id.to_string())); + params.push(("reportFragment", self._report_fragment.to_string())); + for &field in ["reportId", "reportFragment"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/reports/{reportId}/files/{reportFragment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{reportId}", "reportId"), ("{reportFragment}", "reportFragment")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["reportId", "reportFragment"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the report. + pub fn report_id(mut self, new_value: &str) -> ReportGetFileCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *report fragment* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The index of the report fragment to download. + pub fn report_fragment(mut self, new_value: i32) -> ReportGetFileCall<'a, C, NC, A> { + self._report_fragment = new_value; + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGetFileCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGetFileCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGetFileCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Generates and returns a report immediately. +/// +/// A builder for the *generate* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::ReportRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ReportRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().generate(&req) +/// .doit(); +/// # } +/// ``` +pub struct ReportGenerateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: ReportRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGenerateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGenerateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.reports.generate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/reports/generate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ReportRequest) -> ReportGenerateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGenerateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGenerateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Polls for the status of a report request. +/// +/// A builder for the *get* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().get("reportId") +/// .doit(); +/// # } +/// ``` +pub struct ReportGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _report_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.reports.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("reportId", self._report_id.to_string())); + for &field in ["alt", "reportId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{reportId}", "reportId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["reportId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *report id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// ID of the report request being polled. + pub fn report_id(mut self, new_value: &str) -> ReportGetCall<'a, C, NC, A> { + self._report_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a report request into the reporting system. +/// +/// A builder for the *request* method supported by a *report* resource. +/// It is not used directly, but through a `ReportMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-doubleclicksearch2" as doubleclicksearch2; +/// use doubleclicksearch2::ReportRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use doubleclicksearch2::Doubleclicksearch; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Doubleclicksearch::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ReportRequest = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.reports().request(&req) +/// .doit(); +/// # } +/// ``` +pub struct ReportRequestCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Doubleclicksearch, + _request: ReportRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReportRequestCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReportRequestCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Report)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "doubleclicksearch.reports.request", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + for &field in ["alt"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/doubleclicksearch/v2/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ReportRequest) -> ReportRequestCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportRequestCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReportRequestCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportRequestCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/drive2/Cargo.toml b/gen/drive2/Cargo.toml new file mode 100644 index 0000000000..9d353e3ed8 --- /dev/null +++ b/gen/drive2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-drive2" +version = "0.1.0+20150108" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with drive (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/drive2" +homepage = "https://developers.google.com/drive/" +documentation = "http://byron.github.io/google-apis-rs/google-drive2" +license = "MIT" +keywords = ["drive", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/drive2/LICENSE.md b/gen/drive2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/drive2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/drive2/README.md b/gen/drive2/README.md new file mode 100644 index 0000000000..245a684b4e --- /dev/null +++ b/gen/drive2/README.md @@ -0,0 +1,236 @@ + +The `google-drive2` library allows access to all features of the *Google drive* service. + +This documentation was generated from *drive* crate version *0.1.0+20150108*, where *20150108* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *drive* *v2* API can be found at the +[official documentation site](https://developers.google.com/drive/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-drive2/struct.Drive.html) ... + +* [about](http://byron.github.io/google-apis-rs/google-drive2/struct.About.html) + * [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.AboutGetCall.html) +* [apps](http://byron.github.io/google-apis-rs/google-drive2/struct.App.html) + * [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.AppGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.AppListCall.html) +* [changes](http://byron.github.io/google-apis-rs/google-drive2/struct.Change.html) + * [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChangeGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChangeListCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChangeWatchCall.html) +* [channels](http://byron.github.io/google-apis-rs/google-drive2/struct.Channel.html) + * [*stop*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChannelStopCall.html) +* children + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChildrenDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChildrenGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChildrenInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChildrenListCall.html) +* [comments](http://byron.github.io/google-apis-rs/google-drive2/struct.Comment.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.CommentUpdateCall.html) +* [files](http://byron.github.io/google-apis-rs/google-drive2/struct.File.html) + * [*copy*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileCopyCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileDeleteCall.html), [*empty trash*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileEmptyTrashCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.FilePatchCall.html), [*touch*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileTouchCall.html), [*trash*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileTrashCall.html), [*untrash*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileUntrashCall.html), [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileUpdateCall.html) and [*watch*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileWatchCall.html) +* parents + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.ParentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.ParentGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.ParentInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.ParentListCall.html) +* [permissions](http://byron.github.io/google-apis-rs/google-drive2/struct.Permission.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionGetCall.html), [*get id for email*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionGetIdForEmailCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.PermissionUpdateCall.html) +* [properties](http://byron.github.io/google-apis-rs/google-drive2/struct.Property.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.PropertyUpdateCall.html) +* realtime + * [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.RealtimeGetCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.RealtimeUpdateCall.html) +* replies + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.ReplyUpdateCall.html) +* [revisions](http://byron.github.io/google-apis-rs/google-drive2/struct.Revision.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-drive2/struct.RevisionDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-drive2/struct.RevisionGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google-drive2/struct.RevisionListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-drive2/struct.RevisionPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-drive2/struct.RevisionUpdateCall.html) + + +Upload supported by ... + +* [*insert files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileInsertCall.html) +* [*update realtime*](http://byron.github.io/google-apis-rs/google-drive2/struct.RealtimeUpdateCall.html) +* [*update files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileUpdateCall.html) + +Download supported by ... + +* [*watch files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileWatchCall.html) +* [*get files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileGetCall.html) +* [*get realtime*](http://byron.github.io/google-apis-rs/google-drive2/struct.RealtimeGetCall.html) + +Subscription supported by ... + +* [*watch files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileWatchCall.html) +* [*get files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileGetCall.html) +* [*watch changes*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChangeWatchCall.html) +* [*insert files*](http://byron.github.io/google-apis-rs/google-drive2/struct.FileInsertCall.html) +* [*list changes*](http://byron.github.io/google-apis-rs/google-drive2/struct.ChangeListCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-drive2/struct.Drive.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-drive2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-drive2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-drive2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.files().watch(...).doit() +let r = hub.files().empty_trash(...).doit() +let r = hub.files().copy(...).doit() +let r = hub.files().list(...).doit() +let r = hub.files().delete(...).doit() +let r = hub.files().patch(...).doit() +let r = hub.files().update(...).doit() +let r = hub.files().insert(...).doit() +let r = hub.files().untrash(...).doit() +let r = hub.files().trash(...).doit() +let r = hub.files().touch(...).doit() +let r = hub.files().get(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-drive2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-drive2" as drive2; +use drive2::File; +use drive2::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use drive2::Drive; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Drive::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: File = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.files().patch(&req, "fileId") + .use_content_as_indexable_text(true) + .update_viewed_date(false) + .timed_text_track_name("sed") + .timed_text_language("et") + .set_modified_date(true) + .remove_parents("kasd") + .pinned(true) + .ocr_language("takimata") + .ocr(false) + .new_revision(true) + .convert(false) + .add_parents("labore") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-drive2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-drive2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-drive2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-drive2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-drive2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-drive2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-drive2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-drive2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-drive2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-drive2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-drive2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-drive2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-drive2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **drive2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/drive2/src/cmn.rs b/gen/drive2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/drive2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/drive2/src/lib.rs b/gen/drive2/src/lib.rs new file mode 100644 index 0000000000..7d0c04adb6 --- /dev/null +++ b/gen/drive2/src/lib.rs @@ -0,0 +1,19019 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *drive* crate version *0.1.0+20150108*, where *20150108* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *drive* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/drive/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/drive2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Drive.html) ... +//! +//! * [about](struct.About.html) +//! * [*get*](struct.AboutGetCall.html) +//! * [apps](struct.App.html) +//! * [*get*](struct.AppGetCall.html) and [*list*](struct.AppListCall.html) +//! * [changes](struct.Change.html) +//! * [*get*](struct.ChangeGetCall.html), [*list*](struct.ChangeListCall.html) and [*watch*](struct.ChangeWatchCall.html) +//! * [channels](struct.Channel.html) +//! * [*stop*](struct.ChannelStopCall.html) +//! * children +//! * [*delete*](struct.ChildrenDeleteCall.html), [*get*](struct.ChildrenGetCall.html), [*insert*](struct.ChildrenInsertCall.html) and [*list*](struct.ChildrenListCall.html) +//! * [comments](struct.Comment.html) +//! * [*delete*](struct.CommentDeleteCall.html), [*get*](struct.CommentGetCall.html), [*insert*](struct.CommentInsertCall.html), [*list*](struct.CommentListCall.html), [*patch*](struct.CommentPatchCall.html) and [*update*](struct.CommentUpdateCall.html) +//! * [files](struct.File.html) +//! * [*copy*](struct.FileCopyCall.html), [*delete*](struct.FileDeleteCall.html), [*empty trash*](struct.FileEmptyTrashCall.html), [*get*](struct.FileGetCall.html), [*insert*](struct.FileInsertCall.html), [*list*](struct.FileListCall.html), [*patch*](struct.FilePatchCall.html), [*touch*](struct.FileTouchCall.html), [*trash*](struct.FileTrashCall.html), [*untrash*](struct.FileUntrashCall.html), [*update*](struct.FileUpdateCall.html) and [*watch*](struct.FileWatchCall.html) +//! * parents +//! * [*delete*](struct.ParentDeleteCall.html), [*get*](struct.ParentGetCall.html), [*insert*](struct.ParentInsertCall.html) and [*list*](struct.ParentListCall.html) +//! * [permissions](struct.Permission.html) +//! * [*delete*](struct.PermissionDeleteCall.html), [*get*](struct.PermissionGetCall.html), [*get id for email*](struct.PermissionGetIdForEmailCall.html), [*insert*](struct.PermissionInsertCall.html), [*list*](struct.PermissionListCall.html), [*patch*](struct.PermissionPatchCall.html) and [*update*](struct.PermissionUpdateCall.html) +//! * [properties](struct.Property.html) +//! * [*delete*](struct.PropertyDeleteCall.html), [*get*](struct.PropertyGetCall.html), [*insert*](struct.PropertyInsertCall.html), [*list*](struct.PropertyListCall.html), [*patch*](struct.PropertyPatchCall.html) and [*update*](struct.PropertyUpdateCall.html) +//! * realtime +//! * [*get*](struct.RealtimeGetCall.html) and [*update*](struct.RealtimeUpdateCall.html) +//! * replies +//! * [*delete*](struct.ReplyDeleteCall.html), [*get*](struct.ReplyGetCall.html), [*insert*](struct.ReplyInsertCall.html), [*list*](struct.ReplyListCall.html), [*patch*](struct.ReplyPatchCall.html) and [*update*](struct.ReplyUpdateCall.html) +//! * [revisions](struct.Revision.html) +//! * [*delete*](struct.RevisionDeleteCall.html), [*get*](struct.RevisionGetCall.html), [*list*](struct.RevisionListCall.html), [*patch*](struct.RevisionPatchCall.html) and [*update*](struct.RevisionUpdateCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*insert files*](struct.FileInsertCall.html) +//! * [*update realtime*](struct.RealtimeUpdateCall.html) +//! * [*update files*](struct.FileUpdateCall.html) +//! +//! Download supported by ... +//! +//! * [*watch files*](struct.FileWatchCall.html) +//! * [*get files*](struct.FileGetCall.html) +//! * [*get realtime*](struct.RealtimeGetCall.html) +//! +//! Subscription supported by ... +//! +//! * [*watch files*](struct.FileWatchCall.html) +//! * [*get files*](struct.FileGetCall.html) +//! * [*watch changes*](struct.ChangeWatchCall.html) +//! * [*insert files*](struct.FileInsertCall.html) +//! * [*list changes*](struct.ChangeListCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Drive.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.files().watch(...).doit() +//! let r = hub.files().empty_trash(...).doit() +//! let r = hub.files().copy(...).doit() +//! let r = hub.files().list(...).doit() +//! let r = hub.files().delete(...).doit() +//! let r = hub.files().patch(...).doit() +//! let r = hub.files().update(...).doit() +//! let r = hub.files().insert(...).doit() +//! let r = hub.files().untrash(...).doit() +//! let r = hub.files().trash(...).doit() +//! let r = hub.files().touch(...).doit() +//! let r = hub.files().get(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-drive2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-drive2" as drive2; +//! use drive2::File; +//! use drive2::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use drive2::Drive; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Drive::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: File = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.files().patch(&req, "fileId") +//! .use_content_as_indexable_text(false) +//! .update_viewed_date(true) +//! .timed_text_track_name("gubergren") +//! .timed_text_language("sadipscing") +//! .set_modified_date(true) +//! .remove_parents("ea") +//! .pinned(false) +//! .ocr_language("justo") +//! .ocr(true) +//! .new_revision(true) +//! .convert(true) +//! .add_parents("diam") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View and manage the files in your Google Drive + Full, + + /// View your Google Drive apps + AppReadonly, + + /// View and manage Google Drive files that you have opened or created with this app + File, + + /// Modify your Google Apps Script scripts' behavior + Script, + + /// View and manage its own configuration data in your Google Drive + Appdata, + + /// View the files in your Google Drive + Readonly, + + /// View metadata for files in your Google Drive + MetadataReadonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/drive", + Scope::AppReadonly => "https://www.googleapis.com/auth/drive.apps.readonly", + Scope::File => "https://www.googleapis.com/auth/drive.file", + Scope::Script => "https://www.googleapis.com/auth/drive.scripts", + Scope::Appdata => "https://www.googleapis.com/auth/drive.appdata", + Scope::Readonly => "https://www.googleapis.com/auth/drive.readonly", + Scope::MetadataReadonly => "https://www.googleapis.com/auth/drive.metadata.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::AppReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Drive related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// use drive2::File; +/// use drive2::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: File = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().patch(&req, "fileId") +/// .use_content_as_indexable_text(true) +/// .update_viewed_date(true) +/// .timed_text_track_name("duo") +/// .timed_text_language("aliquyam") +/// .set_modified_date(true) +/// .remove_parents("Lorem") +/// .pinned(false) +/// .ocr_language("erat") +/// .ocr(false) +/// .new_revision(true) +/// .convert(true) +/// .add_parents("elitr") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Drive { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Drive {} + +impl<'a, C, NC, A> Drive + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Drive { + Drive { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn about(&'a self) -> AboutMethods<'a, C, NC, A> { + AboutMethods { hub: &self } + } + pub fn apps(&'a self) -> AppMethods<'a, C, NC, A> { + AppMethods { hub: &self } + } + pub fn changes(&'a self) -> ChangeMethods<'a, C, NC, A> { + ChangeMethods { hub: &self } + } + pub fn channels(&'a self) -> ChannelMethods<'a, C, NC, A> { + ChannelMethods { hub: &self } + } + pub fn children(&'a self) -> ChildrenMethods<'a, C, NC, A> { + ChildrenMethods { hub: &self } + } + pub fn comments(&'a self) -> CommentMethods<'a, C, NC, A> { + CommentMethods { hub: &self } + } + pub fn files(&'a self) -> FileMethods<'a, C, NC, A> { + FileMethods { hub: &self } + } + pub fn parents(&'a self) -> ParentMethods<'a, C, NC, A> { + ParentMethods { hub: &self } + } + pub fn permissions(&'a self) -> PermissionMethods<'a, C, NC, A> { + PermissionMethods { hub: &self } + } + pub fn properties(&'a self) -> PropertyMethods<'a, C, NC, A> { + PropertyMethods { hub: &self } + } + pub fn realtime(&'a self) -> RealtimeMethods<'a, C, NC, A> { + RealtimeMethods { hub: &self } + } + pub fn replies(&'a self) -> ReplyMethods<'a, C, NC, A> { + ReplyMethods { hub: &self } + } + pub fn revisions(&'a self) -> RevisionMethods<'a, C, NC, A> { + RevisionMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A reference to a file's parent. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get parents](struct.ParentGetCall.html) (response) +/// * [insert parents](struct.ParentInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ParentReference { + /// Whether or not the parent is the root folder. + #[serde(alias="isRoot")] + pub is_root: Option, + /// This is always drive#parentReference. + pub kind: Option, + /// The ID of the parent. + pub id: Option, + /// A link back to this reference. + #[serde(alias="selfLink")] + pub self_link: Option, + /// A link to the parent. + #[serde(alias="parentLink")] + pub parent_link: Option, +} + +impl RequestValue for ParentReference {} +impl ResponseResult for ParentReference {} + + +/// A JSON representation of a comment on a file in Google Drive. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [update comments](struct.CommentUpdateCall.html) (request|response) +/// * [insert comments](struct.CommentInsertCall.html) (request|response) +/// * [delete comments](struct.CommentDeleteCall.html) (none) +/// * [patch comments](struct.CommentPatchCall.html) (request|response) +/// * [get comments](struct.CommentGetCall.html) (response) +/// * [list comments](struct.CommentListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Comment { + /// The status of this comment. Status can be changed by posting a reply to a comment with the desired status. + /// - "open" - The comment is still open. + /// - "resolved" - The comment has been resolved by one of its replies. + pub status: Option, + /// A link back to this comment. + #[serde(alias="selfLink")] + pub self_link: Option, + /// This is always drive#comment. + pub kind: Option, + /// The user who wrote this comment. + pub author: Option, + /// Whether this comment has been deleted. If a comment has been deleted the content will be cleared and this will only represent a comment that once existed. + pub deleted: Option, + /// The date when this comment was first created. + #[serde(alias="createdDate")] + pub created_date: Option, + /// HTML formatted content for this comment. + #[serde(alias="htmlContent")] + pub html_content: Option, + /// The plain text content used to create this comment. This is not HTML safe and should only be used as a starting point to make edits to a comment's content. + pub content: Option, + /// The date when this comment or any of its replies were last modified. + #[serde(alias="modifiedDate")] + pub modified_date: Option, + /// The context of the file which is being commented on. + pub context: Option, + /// Replies to this post. + pub replies: Option>, + /// The ID of the comment. + #[serde(alias="commentId")] + pub comment_id: Option, + /// A region of the document represented as a JSON string. See anchor documentation for details on how to define and interpret anchor properties. + pub anchor: Option, + /// The title of the file which this comment is addressing. + #[serde(alias="fileTitle")] + pub file_title: Option, + /// The file which this comment is addressing. + #[serde(alias="fileId")] + pub file_id: Option, +} + +impl RequestValue for Comment {} +impl Resource for Comment {} +impl ResponseResult for Comment {} + + +/// An item with user information and settings. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get about](struct.AboutGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct About { + /// The user's language or locale code, as defined by BCP 47, with some extensions from Unicode's LDML format (http://www.unicode.org/reports/tr35/). + #[serde(alias="languageCode")] + pub language_code: String, + /// The amount of storage quota used by different Google services. + #[serde(alias="quotaBytesByService")] + pub quota_bytes_by_service: Vec, + /// List of additional features enabled on this account. + pub features: Vec, + /// The number of quota bytes used by Google Drive. + #[serde(alias="quotaBytesUsed")] + pub quota_bytes_used: String, + /// This is always drive#about. + pub kind: String, + /// Information about supported additional roles per file type. The most specific type takes precedence. + #[serde(alias="additionalRoleInfo")] + pub additional_role_info: Vec, + /// The palette of allowable folder colors as RGB hex strings. + #[serde(alias="folderColorPalette")] + pub folder_color_palette: Vec, + /// The authenticated user. + pub user: User, + /// The type of the user's storage quota. Possible values are: + /// - LIMITED + /// - UNLIMITED + #[serde(alias="quotaType")] + pub quota_type: String, + /// The number of quota bytes used by all Google apps (Drive, Picasa, etc.). + #[serde(alias="quotaBytesUsedAggregate")] + pub quota_bytes_used_aggregate: String, + /// List of max upload sizes for each file type. The most specific type takes precedence. + #[serde(alias="maxUploadSizes")] + pub max_upload_sizes: Vec, + /// The current user's ID as visible in the permissions collection. + #[serde(alias="permissionId")] + pub permission_id: String, + /// The name of the current user. + pub name: String, + /// The total number of quota bytes. + #[serde(alias="quotaBytesTotal")] + pub quota_bytes_total: String, + /// The number of remaining change ids. + #[serde(alias="remainingChangeIds")] + pub remaining_change_ids: String, + /// The ETag of the item. + pub etag: String, + /// The allowable import formats. + #[serde(alias="importFormats")] + pub import_formats: Vec, + /// The id of the root folder. + #[serde(alias="rootFolderId")] + pub root_folder_id: String, + /// The largest change id. + #[serde(alias="largestChangeId")] + pub largest_change_id: String, + /// The number of quota bytes used by trashed items. + #[serde(alias="quotaBytesUsedInTrash")] + pub quota_bytes_used_in_trash: String, + /// The allowable export formats. + #[serde(alias="exportFormats")] + pub export_formats: Vec, + /// The domain sharing policy for the current user. + #[serde(alias="domainSharingPolicy")] + pub domain_sharing_policy: String, + /// A link back to this item. + #[serde(alias="selfLink")] + pub self_link: String, + /// A boolean indicating whether the authenticated app is installed by the authenticated user. + #[serde(alias="isCurrentAppInstalled")] + pub is_current_app_installed: bool, +} + +impl ResponseResult for About {} + + +/// Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed by Google. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileThumbnail { + /// The MIME type of the thumbnail. + #[serde(alias="mimeType")] + pub mime_type: String, + /// The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section 5. + pub image: String, +} + +impl NestedType for FileThumbnail {} +impl Part for FileThumbnail {} + + +/// The metadata for a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [watch files](struct.FileWatchCall.html) (none) +/// * [empty trash files](struct.FileEmptyTrashCall.html) (none) +/// * [copy files](struct.FileCopyCall.html) (request|response) +/// * [list files](struct.FileListCall.html) (none) +/// * [delete files](struct.FileDeleteCall.html) (none) +/// * [patch files](struct.FilePatchCall.html) (request|response) +/// * [update files](struct.FileUpdateCall.html) (request|response) +/// * [insert files](struct.FileInsertCall.html) (request|response) +/// * [untrash files](struct.FileUntrashCall.html) (response) +/// * [trash files](struct.FileTrashCall.html) (response) +/// * [touch files](struct.FileTouchCall.html) (response) +/// * [get files](struct.FileGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct File { + /// The MIME type of the file. This is only mutable on update when uploading new content. This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type. + #[serde(alias="mimeType")] + pub mime_type: Option, + /// Last time this file was viewed by the user (formatted RFC 3339 timestamp). + #[serde(alias="lastViewedByMeDate")] + pub last_viewed_by_me_date: Option, + /// Whether this file is in the Application Data folder. + #[serde(alias="appDataContents")] + pub app_data_contents: Option, + /// A short-lived link to the file's thumbnail. Typically lasts on the order of hours. + #[serde(alias="thumbnailLink")] + pub thumbnail_link: Option, + /// A group of labels for the file. + pub labels: Option, + /// Indexable text attributes for the file (can only be written) + #[serde(alias="indexableText")] + pub indexable_text: Option, + /// Whether this file has been explicitly trashed, as opposed to recursively trashed. This will only be populated if the file is trashed. + #[serde(alias="explicitlyTrashed")] + pub explicitly_trashed: Option, + /// ETag of the file. + pub etag: Option, + /// Name of the last user to modify this file. + #[serde(alias="lastModifyingUserName")] + pub last_modifying_user_name: Option, + /// Whether writers can share the document with other users. + #[serde(alias="writersCanShare")] + pub writers_can_share: Option, + /// Time at which this file was shared with the user (formatted RFC 3339 timestamp). + #[serde(alias="sharedWithMeDate")] + pub shared_with_me_date: Option, + /// User that shared the item with the current user, if available. + #[serde(alias="sharingUser")] + pub sharing_user: Option, + /// Metadata about video media. This will only be present for video types. + #[serde(alias="videoMediaMetadata")] + pub video_media_metadata: Option, + /// The last user to modify this file. + #[serde(alias="lastModifyingUser")] + pub last_modifying_user: Option, + /// Whether the file can be copied by the current user. + pub copyable: Option, + /// Folder color as an RGB hex string if the file is a folder. The list of supported colors is available in the folderColorPalette field of the About resource. If an unsupported color is specified, it will be changed to the closest color in the palette. + #[serde(alias="folderColorRgb")] + pub folder_color_rgb: Option, + /// Name(s) of the owner(s) of this file. + #[serde(alias="ownerNames")] + pub owner_names: Option>, + /// The type of file. This is always drive#file. + pub kind: Option, + /// The ID of the file. + pub id: Option, + /// A link only available on public folders for viewing their static web assets (HTML, CSS, JS, etc) via Google Drive's Website Hosting. + #[serde(alias="webViewLink")] + pub web_view_link: Option, + /// A monotonically increasing version number for the file. This reflects every change made to the file on the server, even those not visible to the requesting user. + pub version: Option, + /// Collection of parent folders which contain this file. + /// Setting this field will put the file in all of the provided folders. On insert, if no folders are provided, the file will be placed in the default root folder. + pub parents: Option>, + /// Links for exporting Google Docs to specific formats. + #[serde(alias="exportLinks")] + pub export_links: Option>, + /// Whether the file has been shared. + pub shared: Option, + /// A link to the file's icon. + #[serde(alias="iconLink")] + pub icon_link: Option, + /// Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed by Google. + pub thumbnail: Option, + /// A map of the id of each of the user's apps to a link to open this file with that app. Only populated when the drive.apps.readonly scope is used. + #[serde(alias="openWithLinks")] + pub open_with_links: Option>, + /// A link to open this file with the user's default app for this file. Only populated when the drive.apps.readonly scope is used. + #[serde(alias="defaultOpenWithLink")] + pub default_open_with_link: Option, + /// A short description of the file. + pub description: Option, + /// A link for downloading the content of the file in a browser using cookie based authentication. In cases where the content is shared publicly, the content can be downloaded without any credentials. + #[serde(alias="webContentLink")] + pub web_content_link: Option, + /// Whether the file can be edited by the current user. + pub editable: Option, + /// A link for embedding the file. + #[serde(alias="embedLink")] + pub embed_link: Option, + /// Time this file was explicitly marked viewed by the user (formatted RFC 3339 timestamp). + #[serde(alias="markedViewedByMeDate")] + pub marked_viewed_by_me_date: Option, + /// The file extension used when downloading this file. This field is read only. To set the extension, include it in the title when creating the file. This is only populated for files with content stored in Drive. + #[serde(alias="fileExtension")] + pub file_extension: Option, + /// The size of the file in bytes. This is only populated for files with content stored in Drive. + #[serde(alias="fileSize")] + pub file_size: Option, + /// Create time for this file (formatted RFC 3339 timestamp). + #[serde(alias="createdDate")] + pub created_date: Option, + /// The list of properties. + pub properties: Option>, + /// An MD5 checksum for the content of this file. This is populated only for files with content stored in Drive. + #[serde(alias="md5Checksum")] + pub md5_checksum: Option, + /// The list of permissions for users with access to this file. + pub permissions: Option>, + /// Metadata about image media. This will only be present for image types, and its contents will depend on what can be parsed from the image content. + #[serde(alias="imageMediaMetadata")] + pub image_media_metadata: Option, + /// The owner(s) of this file. + pub owners: Option>, + /// A link for opening the file in a relevant Google editor or viewer. + #[serde(alias="alternateLink")] + pub alternate_link: Option, + /// The title of this file. + pub title: Option, + /// Last time this file was modified by the user (formatted RFC 3339 timestamp). Note that setting modifiedDate will also update the modifiedByMe date for the user which set the date. + #[serde(alias="modifiedByMeDate")] + pub modified_by_me_date: Option, + /// Short lived download URL for the file. This is only populated for files with content stored in Drive. + #[serde(alias="downloadUrl")] + pub download_url: Option, + /// The permissions for the authenticated user on this file. + #[serde(alias="userPermission")] + pub user_permission: Option, + /// The original filename if the file was uploaded manually, or the original title if the file was inserted through the API. Note that renames of the title will not change the original filename. This will only be populated on files with content stored in Drive. + #[serde(alias="originalFilename")] + pub original_filename: Option, + /// The number of quota bytes used by this file. + #[serde(alias="quotaBytesUsed")] + pub quota_bytes_used: Option, + /// The ID of the file's head revision. This will only be populated for files with content stored in Drive. + #[serde(alias="headRevisionId")] + pub head_revision_id: Option, + /// A link back to this file. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable on update when the setModifiedDate parameter is set. + #[serde(alias="modifiedDate")] + pub modified_date: Option, +} + +impl RequestValue for File {} +impl Resource for File {} +impl ResponseResult for File {} + + +/// Information about supported additional roles per file type. The most specific type takes precedence. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutAdditionalRoleInfo { + /// The supported additional roles per primary role. + #[serde(alias="roleSets")] + pub role_sets: Vec, + /// The content type that this additional role info applies to. + #[serde(alias="type")] + pub type_: String, +} + +impl NestedType for AboutAdditionalRoleInfo {} +impl Part for AboutAdditionalRoleInfo {} + + +/// A list of changes for a user. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list changes](struct.ChangeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChangeList { + /// The page token for the next page of changes. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// This is always drive#changeList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// The current largest change ID. + #[serde(alias="largestChangeId")] + pub largest_change_id: String, + /// The actual list of changes. + pub items: Vec, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// A link to the next page of changes. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for ChangeList {} + + +/// A collection of properties, key-value pairs that are either public or private to an application. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list properties](struct.PropertyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PropertyList { + /// The list of properties. + pub items: Vec, + /// This is always drive#propertyList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// The link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for PropertyList {} + + +/// An ID for a user or group as seen in Permission items. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get id for email permissions](struct.PermissionGetIdForEmailCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PermissionId { + /// This is always drive#permissionId. + pub kind: String, + /// The permission ID. + pub id: String, +} + +impl ResponseResult for PermissionId {} + + +/// Indexable text attributes for the file (can only be written) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileIndexableText { + /// The text to be indexed for this file. + pub text: String, +} + +impl NestedType for FileIndexableText {} +impl Part for FileIndexableText {} + + +/// The supported additional roles per primary role. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutAdditionalRoleInfoRoleSets { + /// A primary permission role. + #[serde(alias="primaryRole")] + pub primary_role: String, + /// The supported additional roles with the primary role. + #[serde(alias="additionalRoles")] + pub additional_roles: Vec, +} + +impl NestedType for AboutAdditionalRoleInfoRoleSets {} +impl Part for AboutAdditionalRoleInfoRoleSets {} + + +/// A JSON representation of a list of replies to a comment on a file in Google Drive. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list replies](struct.ReplyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CommentReplyList { + /// The token to use to request the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of reply. + pub items: Vec, + /// This is always drive#commentReplyList. + pub kind: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// A link to the next page of replies. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for CommentReplyList {} + + +/// The allowable import formats. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutImportFormats { + /// The imported file's content type to convert from. + pub source: String, + /// The possible content types to convert to. + pub targets: Vec, +} + +impl NestedType for AboutImportFormats {} +impl Part for AboutImportFormats {} + + +/// A list of revisions of a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list revisions](struct.RevisionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct RevisionList { + /// The actual list of revisions. + pub items: Vec, + /// This is always drive#revisionList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for RevisionList {} + + +/// List of max upload sizes for each file type. The most specific type takes precedence. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutMaxUploadSizes { + /// The file type. + #[serde(alias="type")] + pub type_: String, + /// The max upload size for this type. + pub size: String, +} + +impl NestedType for AboutMaxUploadSizes {} +impl Part for AboutMaxUploadSizes {} + + +/// A group of labels for the file. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileLabels { + /// Whether viewers are prevented from downloading this file. + pub restricted: bool, + /// Deprecated. + pub hidden: bool, + /// Whether this file has been trashed. This label applies to all users accessing the file; however, only owners are allowed to see and untrash files. + pub trashed: bool, + /// Whether this file is starred by the user. + pub starred: bool, + /// Whether this file has been viewed by this user. + pub viewed: bool, +} + +impl NestedType for FileLabels {} +impl Part for FileLabels {} + + +/// A key-value pair that is either public or private to an application. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert properties](struct.PropertyInsertCall.html) (request|response) +/// * [get properties](struct.PropertyGetCall.html) (response) +/// * [patch properties](struct.PropertyPatchCall.html) (request|response) +/// * [update properties](struct.PropertyUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Property { + /// The link back to this property. + #[serde(alias="selfLink")] + pub self_link: Option, + /// This is always drive#property. + pub kind: Option, + /// ETag of the property. + pub etag: Option, + /// The visibility of this property. + pub visibility: Option, + /// The key of this property. + pub key: Option, + /// The value of this property. + pub value: Option, +} + +impl RequestValue for Property {} +impl ResponseResult for Property {} + + +/// An notification channel used to watch for resource changes. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [watch changes](struct.ChangeWatchCall.html) (request|response) +/// * [watch files](struct.FileWatchCall.html) (request|response) +/// * [stop channels](struct.ChannelStopCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Channel { + /// A version-specific identifier for the watched resource. + #[serde(alias="resourceUri")] + pub resource_uri: Option, + /// Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". + pub kind: Option, + /// An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. + #[serde(alias="resourceId")] + pub resource_id: Option, + /// A UUID or similar unique string that identifies this channel. + pub id: Option, + /// An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. + pub token: Option, + /// Additional parameters controlling delivery channel behavior. Optional. + pub params: Option>, + /// Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. + pub expiration: Option, + /// The address where notifications are delivered for this channel. + pub address: Option, + /// The type of delivery mechanism used for this channel. + #[serde(alias="type")] + pub type_: Option, + /// A Boolean value to indicate whether payload is wanted. Optional. + pub payload: Option, +} + +impl RequestValue for Channel {} +impl Resource for Channel {} +impl ResponseResult for Channel {} + + +/// A revision of a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [delete revisions](struct.RevisionDeleteCall.html) (none) +/// * [update revisions](struct.RevisionUpdateCall.html) (request|response) +/// * [patch revisions](struct.RevisionPatchCall.html) (request|response) +/// * [list revisions](struct.RevisionListCall.html) (none) +/// * [get revisions](struct.RevisionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Revision { + /// The MIME type of the revision. + #[serde(alias="mimeType")] + pub mime_type: Option, + /// A link to the published revision. + #[serde(alias="publishedLink")] + pub published_link: Option, + /// Whether this revision is published outside the domain. This is only populated and can only be modified for Google Docs. + #[serde(alias="publishedOutsideDomain")] + pub published_outside_domain: Option, + /// Whether subsequent revisions will be automatically republished. This is only populated and can only be modified for Google Docs. + #[serde(alias="publishAuto")] + pub publish_auto: Option, + /// The size of the revision in bytes. This will only be populated on files with content stored in Drive. + #[serde(alias="fileSize")] + pub file_size: Option, + /// Name of the last user to modify this revision. + #[serde(alias="lastModifyingUserName")] + pub last_modifying_user_name: Option, + /// The ID of the revision. + pub id: Option, + /// An MD5 checksum for the content of this revision. This will only be populated on files with content stored in Drive. + #[serde(alias="md5Checksum")] + pub md5_checksum: Option, + /// Short term download URL for the file. This will only be populated on files with content stored in Drive. + #[serde(alias="downloadUrl")] + pub download_url: Option, + /// This is always drive#revision. + pub kind: Option, + /// The last user to modify this revision. + #[serde(alias="lastModifyingUser")] + pub last_modifying_user: Option, + /// Whether this revision is pinned to prevent automatic purging. This will only be populated and can only be modified on files with content stored in Drive which are not Google Docs. Revisions can also be pinned when they are created through the drive.files.insert/update/copy by using the pinned query parameter. + pub pinned: Option, + /// The ETag of the revision. + pub etag: Option, + /// The original filename when this revision was created. This will only be populated on files with content stored in Drive. + #[serde(alias="originalFilename")] + pub original_filename: Option, + /// Links for exporting Google Docs to specific formats. + #[serde(alias="exportLinks")] + pub export_links: Option>, + /// Whether this revision is published. This is only populated and can only be modified for Google Docs. + pub published: Option, + /// A link back to this revision. + #[serde(alias="selfLink")] + pub self_link: Option, + /// Last time this revision was modified (formatted RFC 3339 timestamp). + #[serde(alias="modifiedDate")] + pub modified_date: Option, +} + +impl RequestValue for Revision {} +impl Resource for Revision {} +impl ResponseResult for Revision {} + + +/// A JSON representation of a list of comments on a file in Google Drive. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list comments](struct.CommentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct CommentList { + /// The token to use to request the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of comments. + pub items: Vec, + /// This is always drive#commentList. + pub kind: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// A link to the next page of comments. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for CommentList {} + + +/// A list of a file's parents. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list parents](struct.ParentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ParentList { + /// The actual list of parents. + pub items: Vec, + /// This is always drive#parentList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for ParentList {} + + +/// A list of permissions associated with a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list permissions](struct.PermissionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct PermissionList { + /// The actual list of permissions. + pub items: Vec, + /// This is always drive#permissionList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, +} + +impl ResponseResult for PermissionList {} + + +/// The amount of storage quota used by different Google services. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutQuotaBytesByService { + /// The service's name, e.g. DRIVE, GMAIL, or PHOTOS. + #[serde(alias="serviceName")] + pub service_name: String, + /// The storage quota bytes used by the service. + #[serde(alias="bytesUsed")] + pub bytes_used: String, +} + +impl NestedType for AboutQuotaBytesByService {} +impl Part for AboutQuotaBytesByService {} + + +/// A permission for a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch permissions](struct.PermissionPatchCall.html) (request|response) +/// * [list permissions](struct.PermissionListCall.html) (none) +/// * [insert permissions](struct.PermissionInsertCall.html) (request|response) +/// * [get permissions](struct.PermissionGetCall.html) (response) +/// * [get id for email permissions](struct.PermissionGetIdForEmailCall.html) (none) +/// * [delete permissions](struct.PermissionDeleteCall.html) (none) +/// * [update permissions](struct.PermissionUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Permission { + /// Whether the link is required for this permission. + #[serde(alias="withLink")] + pub with_link: Option, + /// The domain name of the entity this permission refers to. This is an output-only field which is present when the permission type is user, group or domain. + pub domain: Option, + /// The name for this permission. + pub name: Option, + /// This is always drive#permission. + pub kind: Option, + /// The email address or domain name for the entity. This is used during inserts and is not populated in responses. When making a drive.permissions.insert request, exactly one of the id or value fields must be specified. + pub value: Option, + /// Additional roles for this user. Only commenter is currently allowed. + #[serde(alias="additionalRoles")] + pub additional_roles: Option>, + /// The authkey parameter required for this permission. + #[serde(alias="authKey")] + pub auth_key: Option, + /// The ETag of the permission. + pub etag: Option, + /// The email address of the user or group this permission refers to. This is an output-only field which is present when the permission type is user or group. + #[serde(alias="emailAddress")] + pub email_address: Option, + /// A link to the profile photo, if available. + #[serde(alias="photoLink")] + pub photo_link: Option, + /// The primary role for this user. Allowed values are: + /// - owner + /// - reader + /// - writer + pub role: Option, + /// The account type. Allowed values are: + /// - user + /// - group + /// - domain + /// - anyone + #[serde(alias="type")] + pub type_: Option, + /// The ID of the user this permission refers to, and identical to the permissionId in the About and Files resources. When making a drive.permissions.insert request, exactly one of the id or value fields must be specified. + pub id: Option, + /// A link back to this permission. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for Permission {} +impl Resource for Permission {} +impl ResponseResult for Permission {} + + +/// Metadata about image media. This will only be present for image types, and its contents will depend on what can be parsed from the image content. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileImageMediaMetadata { + /// The exposure bias of the photo (APEX value). + #[serde(alias="exposureBias")] + pub exposure_bias: f32, + /// The length of the exposure, in seconds. + #[serde(alias="exposureTime")] + pub exposure_time: f32, + /// The smallest f-number of the lens at the focal length used to create the photo (APEX value). + #[serde(alias="maxApertureValue")] + pub max_aperture_value: f32, + /// The color space of the photo. + #[serde(alias="colorSpace")] + pub color_space: String, + /// The height of the image in pixels. + pub height: i32, + /// The lens used to create the photo. + pub lens: String, + /// The aperture used to create the photo (f-number). + pub aperture: f32, + /// The date and time the photo was taken (EXIF format timestamp). + pub date: String, + /// The rotation in clockwise degrees from the image's original orientation. + pub rotation: i32, + /// The white balance mode used to create the photo. + #[serde(alias="whiteBalance")] + pub white_balance: String, + /// The model of the camera used to create the photo. + #[serde(alias="cameraModel")] + pub camera_model: String, + /// Whether a flash was used to create the photo. + #[serde(alias="flashUsed")] + pub flash_used: bool, + /// The make of the camera used to create the photo. + #[serde(alias="cameraMake")] + pub camera_make: String, + /// The focal length used to create the photo, in millimeters. + #[serde(alias="focalLength")] + pub focal_length: f32, + /// The exposure mode used to create the photo. + #[serde(alias="exposureMode")] + pub exposure_mode: String, + /// The distance to the subject of the photo, in meters. + #[serde(alias="subjectDistance")] + pub subject_distance: i32, + /// The width of the image in pixels. + pub width: i32, + /// The metering mode used to create the photo. + #[serde(alias="meteringMode")] + pub metering_mode: String, + /// Geographic location information stored in the image. + pub location: FileImageMediaMetadataLocation, + /// The ISO speed used to create the photo. + #[serde(alias="isoSpeed")] + pub iso_speed: i32, + /// The type of sensor used to create the photo. + pub sensor: String, +} + +impl NestedType for FileImageMediaMetadata {} +impl Part for FileImageMediaMetadata {} + + +/// The apps resource provides a list of the apps that a user has installed, with information about each app's supported MIME types, file extensions, and other details. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get apps](struct.AppGetCall.html) (response) +/// * [list apps](struct.AppListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct App { + /// The list of secondary mime types. + #[serde(alias="secondaryMimeTypes")] + pub secondary_mime_types: Vec, + /// Whether the app is selected as the default handler for the types it supports. + #[serde(alias="useByDefault")] + pub use_by_default: bool, + /// Whether the app is installed. + pub installed: bool, + /// A link to the product listing for this app. + #[serde(alias="productUrl")] + pub product_url: String, + /// Whether this app supports importing Google Docs. + #[serde(alias="supportsImport")] + pub supports_import: bool, + /// Whether this app supports creating new objects. + #[serde(alias="supportsCreate")] + pub supports_create: bool, + /// A long description of the app. + #[serde(alias="longDescription")] + pub long_description: String, + /// A short description of the app. + #[serde(alias="shortDescription")] + pub short_description: String, + /// The ID of the app. + pub id: String, + /// Whether the app has drive-wide scope. An app with drive-wide scope can access all files in the user's drive. + #[serde(alias="hasDriveWideScope")] + pub has_drive_wide_scope: bool, + /// The type of object this app creates (e.g. Chart). If empty, the app name should be used instead. + #[serde(alias="objectType")] + pub object_type: String, + /// This is always drive#app. + pub kind: String, + /// The list of primary file extensions. + #[serde(alias="primaryFileExtensions")] + pub primary_file_extensions: Vec, + /// The list of primary mime types. + #[serde(alias="primaryMimeTypes")] + pub primary_mime_types: Vec, + /// The url to create a new file with this app. + #[serde(alias="createUrl")] + pub create_url: String, + /// The various icons for the app. + pub icons: Vec, + /// Whether this app supports creating new files when offline. + #[serde(alias="supportsOfflineCreate")] + pub supports_offline_create: bool, + /// The list of secondary file extensions. + #[serde(alias="secondaryFileExtensions")] + pub secondary_file_extensions: Vec, + /// The name of the app. + pub name: String, + /// Whether the app is authorized to access data on the user's Drive. + pub authorized: bool, + /// Whether this app supports opening more than one file. + #[serde(alias="supportsMultiOpen")] + pub supports_multi_open: bool, + /// The template url to create a new file with this app in a given folder. The template will contain {folderId} to be replaced by the folder to create the new file in. + #[serde(alias="createInFolderTemplate")] + pub create_in_folder_template: String, + /// The template url for opening files with this app. The template will contain {ids} and/or {exportIds} to be replaced by the actual file ids. + #[serde(alias="openUrlTemplate")] + pub open_url_template: String, + /// The ID of the product listing for this app. + #[serde(alias="productId")] + pub product_id: String, +} + +impl Resource for App {} +impl ResponseResult for App {} + + +/// Geographic location information stored in the image. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileImageMediaMetadataLocation { + /// The latitude stored in the image. + pub latitude: f64, + /// The altitude stored in the image. + pub altitude: f64, + /// The longitude stored in the image. + pub longitude: f64, +} + +impl NestedType for FileImageMediaMetadataLocation {} +impl Part for FileImageMediaMetadataLocation {} + + +/// A list of files. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list files](struct.FileListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct FileList { + /// The page token for the next page of files. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// This is always drive#fileList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// The actual list of files. + pub items: Vec, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// A link to the next page of files. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for FileList {} + + +/// A list of children of a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list children](struct.ChildrenListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ChildList { + /// The page token for the next page of children. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// This is always drive#childList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// The actual list of children. + pub items: Vec, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// A link to the next page of children. + #[serde(alias="nextLink")] + pub next_link: String, +} + +impl ResponseResult for ChildList {} + + +/// A JSON representation of a reply to a comment on a file in Google Drive. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch replies](struct.ReplyPatchCall.html) (request|response) +/// * [insert replies](struct.ReplyInsertCall.html) (request|response) +/// * [get replies](struct.ReplyGetCall.html) (response) +/// * [update replies](struct.ReplyUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentReply { + /// This is always drive#commentReply. + pub kind: Option, + /// The user who wrote this reply. + pub author: Option, + /// Whether this reply has been deleted. If a reply has been deleted the content will be cleared and this will only represent a reply that once existed. + pub deleted: Option, + /// HTML formatted content for this reply. + #[serde(alias="htmlContent")] + pub html_content: Option, + /// The plain text content used to create this reply. This is not HTML safe and should only be used as a starting point to make edits to a reply's content. This field is required on inserts if no verb is specified (resolve/reopen). + pub content: Option, + /// The action this reply performed to the parent comment. When creating a new reply this is the action to be perform to the parent comment. Possible values are: + /// - "resolve" - To resolve a comment. + /// - "reopen" - To reopen (un-resolve) a comment. + pub verb: Option, + /// The ID of the reply. + #[serde(alias="replyId")] + pub reply_id: Option, + /// The date when this reply was last modified. + #[serde(alias="modifiedDate")] + pub modified_date: Option, + /// The date when this reply was first created. + #[serde(alias="createdDate")] + pub created_date: Option, +} + +impl RequestValue for CommentReply {} +impl ResponseResult for CommentReply {} + + +/// The user's profile picture. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserPicture { + /// A URL that points to a profile picture of this user. + pub url: String, +} + +impl NestedType for UserPicture {} +impl Part for UserPicture {} + + +/// List of additional features enabled on this account. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutFeatures { + /// The name of the feature. + #[serde(alias="featureName")] + pub feature_name: String, + /// The request limit rate for this feature, in queries per second. + #[serde(alias="featureRate")] + pub feature_rate: f64, +} + +impl NestedType for AboutFeatures {} +impl Part for AboutFeatures {} + + +/// The JSON template for a user. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct User { + /// The user's profile picture. + pub picture: UserPicture, + /// This is always drive#user. + pub kind: String, + /// Whether this user is the same as the authenticated user for whom the request was made. + #[serde(alias="isAuthenticatedUser")] + pub is_authenticated_user: bool, + /// A plain text displayable name for this user. + #[serde(alias="displayName")] + pub display_name: String, + /// The email address of the user. + #[serde(alias="emailAddress")] + pub email_address: String, + /// The user's ID as visible in the permissions collection. + #[serde(alias="permissionId")] + pub permission_id: String, +} + +impl Part for User {} + + +/// A list of third-party applications which the user has installed or given access to Google Drive. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list apps](struct.AppListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AppList { + /// The actual list of apps. + pub items: Vec, + /// This is always drive#appList. + pub kind: String, + /// The ETag of the list. + pub etag: String, + /// A link back to this list. + #[serde(alias="selfLink")] + pub self_link: String, + /// List of app IDs that the user has specified to use by default. The list is in reverse-priority order (lowest to highest). + #[serde(alias="defaultAppIds")] + pub default_app_ids: Vec, +} + +impl ResponseResult for AppList {} + + +/// The various icons for the app. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AppIcons { + /// Category of the icon. Allowed values are: + /// - application - icon for the application + /// - document - icon for a file associated with the app + /// - documentShared - icon for a shared file associated with the app + pub category: String, + /// URL for the icon. + #[serde(alias="iconUrl")] + pub icon_url: String, + /// Size of the icon. Represented as the maximum of the width and height. + pub size: i32, +} + +impl NestedType for AppIcons {} +impl Part for AppIcons {} + + +/// The context of the file which is being commented on. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentContext { + /// The MIME type of the context snippet. + #[serde(alias="type")] + pub type_: String, + /// Data representation of the segment of the file being commented on. In the case of a text file for example, this would be the actual text that the comment is about. + pub value: String, +} + +impl NestedType for CommentContext {} +impl Part for CommentContext {} + + +/// A reference to a folder's child. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [insert children](struct.ChildrenInsertCall.html) (request|response) +/// * [get children](struct.ChildrenGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ChildReference { + /// This is always drive#childReference. + pub kind: Option, + /// A link to the child. + #[serde(alias="childLink")] + pub child_link: Option, + /// The ID of the child. + pub id: Option, + /// A link back to this reference. + #[serde(alias="selfLink")] + pub self_link: Option, +} + +impl RequestValue for ChildReference {} +impl ResponseResult for ChildReference {} + + +/// Metadata about video media. This will only be present for video types. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileVideoMediaMetadata { + /// The width of the video in pixels. + pub width: i32, + /// The duration of the video in milliseconds. + #[serde(alias="durationMillis")] + pub duration_millis: String, + /// The height of the video in pixels. + pub height: i32, +} + +impl NestedType for FileVideoMediaMetadata {} +impl Part for FileVideoMediaMetadata {} + + +/// The allowable export formats. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct AboutExportFormats { + /// The content type to convert from. + pub source: String, + /// The possible content types to convert to. + pub targets: Vec, +} + +impl NestedType for AboutExportFormats {} +impl Part for AboutExportFormats {} + + +/// Representation of a change to a file. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list changes](struct.ChangeListCall.html) (none) +/// * [watch changes](struct.ChangeWatchCall.html) (none) +/// * [get changes](struct.ChangeGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Change { + /// The time of this modification. + #[serde(alias="modificationDate")] + pub modification_date: String, + /// This is always drive#change. + pub kind: String, + /// The updated state of the file. Present if the file has not been deleted. + pub file: File, + /// Whether the file has been deleted. + pub deleted: bool, + /// The ID of the change. + pub id: String, + /// A link back to this change. + #[serde(alias="selfLink")] + pub self_link: String, + /// The ID of the file associated with this change. + #[serde(alias="fileId")] + pub file_id: String, +} + +impl Resource for Change {} +impl ResponseResult for Change {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *file* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `copy(...)`, `delete(...)`, `empty_trash(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `touch(...)`, `trash(...)`, `untrash(...)`, `update(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.files(); +/// # } +/// ``` +pub struct FileMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for FileMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Subscribe to changes on a file + pub fn watch(&self, request: &Channel, file_id: &str) -> FileWatchCall<'a, C, NC, A> { + FileWatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _update_viewed_date: Default::default(), + _projection: Default::default(), + _acknowledge_abuse: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Insert a new file. + pub fn insert(&self, request: &File) -> FileInsertCall<'a, C, NC, A> { + FileInsertCall { + hub: self.hub, + _request: request.clone(), + _visibility: Default::default(), + _use_content_as_indexable_text: Default::default(), + _timed_text_track_name: Default::default(), + _timed_text_language: Default::default(), + _pinned: Default::default(), + _ocr_language: Default::default(), + _ocr: Default::default(), + _convert: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Restores a file from the trash. + pub fn untrash(&self, file_id: &str) -> FileUntrashCall<'a, C, NC, A> { + FileUntrashCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a copy of the specified file. + pub fn copy(&self, request: &File, file_id: &str) -> FileCopyCall<'a, C, NC, A> { + FileCopyCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _visibility: Default::default(), + _timed_text_track_name: Default::default(), + _timed_text_language: Default::default(), + _pinned: Default::default(), + _ocr_language: Default::default(), + _ocr: Default::default(), + _convert: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Moves a file to the trash. + pub fn trash(&self, file_id: &str) -> FileTrashCall<'a, C, NC, A> { + FileTrashCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Permanently deletes all of the user's trashed files. + pub fn empty_trash(&self) -> FileEmptyTrashCall<'a, C, NC, A> { + FileEmptyTrashCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the user's files. + pub fn list(&self) -> FileListCall<'a, C, NC, A> { + FileListCall { + hub: self.hub, + _q: Default::default(), + _projection: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _corpus: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Set the file's updated time to the current server time. + pub fn touch(&self, file_id: &str) -> FileTouchCall<'a, C, NC, A> { + FileTouchCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates file metadata and/or content. + pub fn update(&self, request: &File, file_id: &str) -> FileUpdateCall<'a, C, NC, A> { + FileUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _use_content_as_indexable_text: Default::default(), + _update_viewed_date: Default::default(), + _timed_text_track_name: Default::default(), + _timed_text_language: Default::default(), + _set_modified_date: Default::default(), + _remove_parents: Default::default(), + _pinned: Default::default(), + _ocr_language: Default::default(), + _ocr: Default::default(), + _new_revision: Default::default(), + _convert: Default::default(), + _add_parents: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Permanently deletes a file by ID. Skips the trash. The currently authenticated user must own the file. + pub fn delete(&self, file_id: &str) -> FileDeleteCall<'a, C, NC, A> { + FileDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates file metadata and/or content. This method supports patch semantics. + pub fn patch(&self, request: &File, file_id: &str) -> FilePatchCall<'a, C, NC, A> { + FilePatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _use_content_as_indexable_text: Default::default(), + _update_viewed_date: Default::default(), + _timed_text_track_name: Default::default(), + _timed_text_language: Default::default(), + _set_modified_date: Default::default(), + _remove_parents: Default::default(), + _pinned: Default::default(), + _ocr_language: Default::default(), + _ocr: Default::default(), + _new_revision: Default::default(), + _convert: Default::default(), + _add_parents: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a file's metadata by ID. + pub fn get(&self, file_id: &str) -> FileGetCall<'a, C, NC, A> { + FileGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _update_viewed_date: Default::default(), + _projection: Default::default(), + _acknowledge_abuse: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *about* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` +/// // to build up your call. +/// let rb = hub.about(); +/// # } +/// ``` +pub struct AboutMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AboutMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AboutMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the information about the current user along with Drive API settings + pub fn get(&self) -> AboutGetCall<'a, C, NC, A> { + AboutGetCall { + hub: self.hub, + _start_change_id: Default::default(), + _max_change_id_count: Default::default(), + _include_subscribed: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *realtime* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.realtime(); +/// # } +/// ``` +pub struct RealtimeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RealtimeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RealtimeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Overwrites the Realtime API data model associated with this file with the provided JSON data model. + pub fn update(&self, file_id: &str) -> RealtimeUpdateCall<'a, C, NC, A> { + RealtimeUpdateCall { + hub: self.hub, + _file_id: file_id.to_string(), + _base_revision: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Exports the contents of the Realtime API data model associated with this file as JSON. + pub fn get(&self, file_id: &str) -> RealtimeGetCall<'a, C, NC, A> { + RealtimeGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _revision: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *app* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.apps(); +/// # } +/// ``` +pub struct AppMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for AppMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> AppMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific app. + pub fn get(&self, app_id: &str) -> AppGetCall<'a, C, NC, A> { + AppGetCall { + hub: self.hub, + _app_id: app_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists a user's installed apps. + pub fn list(&self) -> AppListCall<'a, C, NC, A> { + AppListCall { + hub: self.hub, + _language_code: Default::default(), + _app_filter_mime_types: Default::default(), + _app_filter_extensions: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *comment* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.comments(); +/// # } +/// ``` +pub struct CommentMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for CommentMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes a comment. + pub fn delete(&self, file_id: &str, comment_id: &str) -> CommentDeleteCall<'a, C, NC, A> { + CommentDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a comment by ID. + pub fn get(&self, file_id: &str, comment_id: &str) -> CommentGetCall<'a, C, NC, A> { + CommentGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new comment on the given file. + pub fn insert(&self, request: &Comment, file_id: &str) -> CommentInsertCall<'a, C, NC, A> { + CommentInsertCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing comment. This method supports patch semantics. + pub fn patch(&self, request: &Comment, file_id: &str, comment_id: &str) -> CommentPatchCall<'a, C, NC, A> { + CommentPatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing comment. + pub fn update(&self, request: &Comment, file_id: &str, comment_id: &str) -> CommentUpdateCall<'a, C, NC, A> { + CommentUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists a file's comments. + pub fn list(&self, file_id: &str) -> CommentListCall<'a, C, NC, A> { + CommentListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _updated_min: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *children* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.children(); +/// # } +/// ``` +pub struct ChildrenMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChildrenMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChildrenMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists a folder's children. + pub fn list(&self, folder_id: &str) -> ChildrenListCall<'a, C, NC, A> { + ChildrenListCall { + hub: self.hub, + _folder_id: folder_id.to_string(), + _q: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific child reference. + pub fn get(&self, folder_id: &str, child_id: &str) -> ChildrenGetCall<'a, C, NC, A> { + ChildrenGetCall { + hub: self.hub, + _folder_id: folder_id.to_string(), + _child_id: child_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a child from a folder. + pub fn delete(&self, folder_id: &str, child_id: &str) -> ChildrenDeleteCall<'a, C, NC, A> { + ChildrenDeleteCall { + hub: self.hub, + _folder_id: folder_id.to_string(), + _child_id: child_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a file into a folder. + pub fn insert(&self, request: &ChildReference, folder_id: &str) -> ChildrenInsertCall<'a, C, NC, A> { + ChildrenInsertCall { + hub: self.hub, + _request: request.clone(), + _folder_id: folder_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *channel* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `stop(...)` +/// // to build up your call. +/// let rb = hub.channels(); +/// # } +/// ``` +pub struct ChannelMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChannelMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Stop watching resources through this channel + pub fn stop(&self, request: &Channel) -> ChannelStopCall<'a, C, NC, A> { + ChannelStopCall { + hub: self.hub, + _request: request.clone(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *parent* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.parents(); +/// # } +/// ``` +pub struct ParentMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ParentMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ParentMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists a file's parents. + pub fn list(&self, file_id: &str) -> ParentListCall<'a, C, NC, A> { + ParentListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a parent from a file. + pub fn delete(&self, file_id: &str, parent_id: &str) -> ParentDeleteCall<'a, C, NC, A> { + ParentDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _parent_id: parent_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a parent folder for a file. + pub fn insert(&self, request: &ParentReference, file_id: &str) -> ParentInsertCall<'a, C, NC, A> { + ParentInsertCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific parent reference. + pub fn get(&self, file_id: &str, parent_id: &str) -> ParentGetCall<'a, C, NC, A> { + ParentGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _parent_id: parent_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *reply* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.replies(); +/// # } +/// ``` +pub struct ReplyMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ReplyMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing reply. This method supports patch semantics. + pub fn patch(&self, request: &CommentReply, file_id: &str, comment_id: &str, reply_id: &str) -> ReplyPatchCall<'a, C, NC, A> { + ReplyPatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _reply_id: reply_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all of the replies to a comment. + pub fn list(&self, file_id: &str, comment_id: &str) -> ReplyListCall<'a, C, NC, A> { + ReplyListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a reply. + pub fn get(&self, file_id: &str, comment_id: &str, reply_id: &str) -> ReplyGetCall<'a, C, NC, A> { + ReplyGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _reply_id: reply_id.to_string(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new reply to the given comment. + pub fn insert(&self, request: &CommentReply, file_id: &str, comment_id: &str) -> ReplyInsertCall<'a, C, NC, A> { + ReplyInsertCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a reply. + pub fn delete(&self, file_id: &str, comment_id: &str, reply_id: &str) -> ReplyDeleteCall<'a, C, NC, A> { + ReplyDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _reply_id: reply_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing reply. + pub fn update(&self, request: &CommentReply, file_id: &str, comment_id: &str, reply_id: &str) -> ReplyUpdateCall<'a, C, NC, A> { + ReplyUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _comment_id: comment_id.to_string(), + _reply_id: reply_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *permission* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `get_id_for_email(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.permissions(); +/// # } +/// ``` +pub struct PermissionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PermissionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes a permission from a file. + pub fn delete(&self, file_id: &str, permission_id: &str) -> PermissionDeleteCall<'a, C, NC, A> { + PermissionDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _permission_id: permission_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a permission for a file. + pub fn insert(&self, request: &Permission, file_id: &str) -> PermissionInsertCall<'a, C, NC, A> { + PermissionInsertCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _send_notification_emails: Default::default(), + _email_message: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a permission. + pub fn update(&self, request: &Permission, file_id: &str, permission_id: &str) -> PermissionUpdateCall<'a, C, NC, A> { + PermissionUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _permission_id: permission_id.to_string(), + _transfer_ownership: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a permission. This method supports patch semantics. + pub fn patch(&self, request: &Permission, file_id: &str, permission_id: &str) -> PermissionPatchCall<'a, C, NC, A> { + PermissionPatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _permission_id: permission_id.to_string(), + _transfer_ownership: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists a file's permissions. + pub fn list(&self, file_id: &str) -> PermissionListCall<'a, C, NC, A> { + PermissionListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a permission by ID. + pub fn get(&self, file_id: &str, permission_id: &str) -> PermissionGetCall<'a, C, NC, A> { + PermissionGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _permission_id: permission_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the permission ID for an email address. + pub fn get_id_for_email(&self, email: &str) -> PermissionGetIdForEmailCall<'a, C, NC, A> { + PermissionGetIdForEmailCall { + hub: self.hub, + _email: email.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *change* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)` and `watch(...)` +/// // to build up your call. +/// let rb = hub.changes(); +/// # } +/// ``` +pub struct ChangeMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for ChangeMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Subscribe to changes for a user. + pub fn watch(&self, request: &Channel) -> ChangeWatchCall<'a, C, NC, A> { + ChangeWatchCall { + hub: self.hub, + _request: request.clone(), + _start_change_id: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_subscribed: Default::default(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the changes for a user. + pub fn list(&self) -> ChangeListCall<'a, C, NC, A> { + ChangeListCall { + hub: self.hub, + _start_change_id: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _include_subscribed: Default::default(), + _include_deleted: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific change. + pub fn get(&self, change_id: &str) -> ChangeGetCall<'a, C, NC, A> { + ChangeGetCall { + hub: self.hub, + _change_id: change_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *property* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.properties(); +/// # } +/// ``` +pub struct PropertyMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for PropertyMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates a property. This method supports patch semantics. + pub fn patch(&self, request: &Property, file_id: &str, property_key: &str) -> PropertyPatchCall<'a, C, NC, A> { + PropertyPatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _property_key: property_key.to_string(), + _visibility: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a property. + pub fn delete(&self, file_id: &str, property_key: &str) -> PropertyDeleteCall<'a, C, NC, A> { + PropertyDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _property_key: property_key.to_string(), + _visibility: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a property to a file. + pub fn insert(&self, request: &Property, file_id: &str) -> PropertyInsertCall<'a, C, NC, A> { + PropertyInsertCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists a file's properties. + pub fn list(&self, file_id: &str) -> PropertyListCall<'a, C, NC, A> { + PropertyListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a property. + pub fn update(&self, request: &Property, file_id: &str, property_key: &str) -> PropertyUpdateCall<'a, C, NC, A> { + PropertyUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _property_key: property_key.to_string(), + _visibility: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a property by its key. + pub fn get(&self, file_id: &str, property_key: &str) -> PropertyGetCall<'a, C, NC, A> { + PropertyGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _property_key: property_key.to_string(), + _visibility: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *revision* resources. +/// It is not used directly, but through the `Drive` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-drive2" as drive2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use drive2::Drive; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Drive::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.revisions(); +/// # } +/// ``` +pub struct RevisionMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for RevisionMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific revision. + pub fn get(&self, file_id: &str, revision_id: &str) -> RevisionGetCall<'a, C, NC, A> { + RevisionGetCall { + hub: self.hub, + _file_id: file_id.to_string(), + _revision_id: revision_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes a revision. + pub fn delete(&self, file_id: &str, revision_id: &str) -> RevisionDeleteCall<'a, C, NC, A> { + RevisionDeleteCall { + hub: self.hub, + _file_id: file_id.to_string(), + _revision_id: revision_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a revision. + pub fn update(&self, request: &Revision, file_id: &str, revision_id: &str) -> RevisionUpdateCall<'a, C, NC, A> { + RevisionUpdateCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _revision_id: revision_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists a file's revisions. + pub fn list(&self, file_id: &str) -> RevisionListCall<'a, C, NC, A> { + RevisionListCall { + hub: self.hub, + _file_id: file_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a revision. This method supports patch semantics. + pub fn patch(&self, request: &Revision, file_id: &str, revision_id: &str) -> RevisionPatchCall<'a, C, NC, A> { + RevisionPatchCall { + hub: self.hub, + _request: request.clone(), + _file_id: file_id.to_string(), + _revision_id: revision_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Subscribe to changes on a file +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `Channel` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *watch* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().watch(&req, "fileId") +/// .update_viewed_date(false) +/// .projection("labore") +/// .acknowledge_abuse(true) +/// .doit(); +/// # } +/// ``` +pub struct FileWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Channel, + _file_id: String, + _update_viewed_date: Option, + _projection: Option, + _acknowledge_abuse: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._update_viewed_date { + params.push(("updateViewedDate", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._acknowledge_abuse { + params.push(("acknowledgeAbuse", value.to_string())); + } + for &field in ["fileId", "updateViewedDate", "projection", "acknowledgeAbuse"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> FileWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file in question. + pub fn file_id(mut self, new_value: &str) -> FileWatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *update viewed date* query property to the given value. + /// + /// + /// Whether to update the view date after successfully retrieving the file. + pub fn update_viewed_date(mut self, new_value: bool) -> FileWatchCall<'a, C, NC, A> { + self._update_viewed_date = Some(new_value); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// This parameter is deprecated and has no function. + pub fn projection(mut self, new_value: &str) -> FileWatchCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *acknowledge abuse* query property to the given value. + /// + /// + /// Whether the user is acknowledging the risk of downloading known malware or other abusive files. + pub fn acknowledge_abuse(mut self, new_value: bool) -> FileWatchCall<'a, C, NC, A> { + self._acknowledge_abuse = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Insert a new file. +/// +/// A builder for the *insert* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::File; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: File = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().insert(&req) +/// .visibility("dolore") +/// .use_content_as_indexable_text(true) +/// .timed_text_track_name("aliquyam") +/// .timed_text_language("accusam") +/// .pinned(false) +/// .ocr_language("sea") +/// .ocr(true) +/// .convert(false) +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct FileInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: File, + _visibility: Option, + _use_content_as_indexable_text: Option, + _timed_text_track_name: Option, + _timed_text_language: Option, + _pinned: Option, + _ocr_language: Option, + _ocr: Option, + _convert: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + if let Some(value) = self._use_content_as_indexable_text { + params.push(("useContentAsIndexableText", value.to_string())); + } + if let Some(value) = self._timed_text_track_name { + params.push(("timedTextTrackName", value.to_string())); + } + if let Some(value) = self._timed_text_language { + params.push(("timedTextLanguage", value.to_string())); + } + if let Some(value) = self._pinned { + params.push(("pinned", value.to_string())); + } + if let Some(value) = self._ocr_language { + params.push(("ocrLanguage", value.to_string())); + } + if let Some(value) = self._ocr { + params.push(("ocr", value.to_string())); + } + if let Some(value) = self._convert { + params.push(("convert", value.to_string())); + } + for &field in ["alt", "visibility", "useContentAsIndexableText", "timedTextTrackName", "timedTextLanguage", "pinned", "ocrLanguage", "ocr", "convert"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/drive/v2/files".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/drive/v2/files".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut mp_reader: MultiPartReader = Default::default(); + let (mut body_reader, content_type) = match protocol { + "simple" => { + mp_reader.reserve_exact(2); + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone()) + .add_part(&mut reader, size, reader_mime_type.clone()); + let mime_type = mp_reader.mime_type(); + (&mut mp_reader as &mut io::Read, ContentType(mime_type)) + }, + _ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())), + }; + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(content_type) + .body(&mut body_reader); + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 5120GB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 5120GB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &File) -> FileInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the new file. This parameter is only relevant when convert=false. + pub fn visibility(mut self, new_value: &str) -> FileInsertCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *use content as indexable text* query property to the given value. + /// + /// + /// Whether to use the content as indexable text. + pub fn use_content_as_indexable_text(mut self, new_value: bool) -> FileInsertCall<'a, C, NC, A> { + self._use_content_as_indexable_text = Some(new_value); + self + } + /// Sets the *timed text track name* query property to the given value. + /// + /// + /// The timed text track name. + pub fn timed_text_track_name(mut self, new_value: &str) -> FileInsertCall<'a, C, NC, A> { + self._timed_text_track_name = Some(new_value.to_string()); + self + } + /// Sets the *timed text language* query property to the given value. + /// + /// + /// The language of the timed text. + pub fn timed_text_language(mut self, new_value: &str) -> FileInsertCall<'a, C, NC, A> { + self._timed_text_language = Some(new_value.to_string()); + self + } + /// Sets the *pinned* query property to the given value. + /// + /// + /// Whether to pin the head revision of the uploaded file. A file can have a maximum of 200 pinned revisions. + pub fn pinned(mut self, new_value: bool) -> FileInsertCall<'a, C, NC, A> { + self._pinned = Some(new_value); + self + } + /// Sets the *ocr language* query property to the given value. + /// + /// + /// If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes. + pub fn ocr_language(mut self, new_value: &str) -> FileInsertCall<'a, C, NC, A> { + self._ocr_language = Some(new_value.to_string()); + self + } + /// Sets the *ocr* query property to the given value. + /// + /// + /// Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. + pub fn ocr(mut self, new_value: bool) -> FileInsertCall<'a, C, NC, A> { + self._ocr = Some(new_value); + self + } + /// Sets the *convert* query property to the given value. + /// + /// + /// Whether to convert this file to the corresponding Google Docs format. + pub fn convert(mut self, new_value: bool) -> FileInsertCall<'a, C, NC, A> { + self._convert = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Restores a file from the trash. +/// +/// A builder for the *untrash* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().untrash("fileId") +/// .doit(); +/// # } +/// ``` +pub struct FileUntrashCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileUntrashCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileUntrashCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.untrash", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/untrash".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to untrash. + pub fn file_id(mut self, new_value: &str) -> FileUntrashCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileUntrashCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileUntrashCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileUntrashCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a copy of the specified file. +/// +/// A builder for the *copy* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::File; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: File = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().copy(&req, "fileId") +/// .visibility("sanctus") +/// .timed_text_track_name("et") +/// .timed_text_language("amet") +/// .pinned(true) +/// .ocr_language("consetetur") +/// .ocr(true) +/// .convert(true) +/// .doit(); +/// # } +/// ``` +pub struct FileCopyCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: File, + _file_id: String, + _visibility: Option, + _timed_text_track_name: Option, + _timed_text_language: Option, + _pinned: Option, + _ocr_language: Option, + _ocr: Option, + _convert: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileCopyCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileCopyCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.copy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((11 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + if let Some(value) = self._timed_text_track_name { + params.push(("timedTextTrackName", value.to_string())); + } + if let Some(value) = self._timed_text_language { + params.push(("timedTextLanguage", value.to_string())); + } + if let Some(value) = self._pinned { + params.push(("pinned", value.to_string())); + } + if let Some(value) = self._ocr_language { + params.push(("ocrLanguage", value.to_string())); + } + if let Some(value) = self._ocr { + params.push(("ocr", value.to_string())); + } + if let Some(value) = self._convert { + params.push(("convert", value.to_string())); + } + for &field in ["alt", "fileId", "visibility", "timedTextTrackName", "timedTextLanguage", "pinned", "ocrLanguage", "ocr", "convert"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/copy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &File) -> FileCopyCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to copy. + pub fn file_id(mut self, new_value: &str) -> FileCopyCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the new file. This parameter is only relevant when the source is not a native Google Doc and convert=false. + pub fn visibility(mut self, new_value: &str) -> FileCopyCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *timed text track name* query property to the given value. + /// + /// + /// The timed text track name. + pub fn timed_text_track_name(mut self, new_value: &str) -> FileCopyCall<'a, C, NC, A> { + self._timed_text_track_name = Some(new_value.to_string()); + self + } + /// Sets the *timed text language* query property to the given value. + /// + /// + /// The language of the timed text. + pub fn timed_text_language(mut self, new_value: &str) -> FileCopyCall<'a, C, NC, A> { + self._timed_text_language = Some(new_value.to_string()); + self + } + /// Sets the *pinned* query property to the given value. + /// + /// + /// Whether to pin the head revision of the new copy. A file can have a maximum of 200 pinned revisions. + pub fn pinned(mut self, new_value: bool) -> FileCopyCall<'a, C, NC, A> { + self._pinned = Some(new_value); + self + } + /// Sets the *ocr language* query property to the given value. + /// + /// + /// If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes. + pub fn ocr_language(mut self, new_value: &str) -> FileCopyCall<'a, C, NC, A> { + self._ocr_language = Some(new_value.to_string()); + self + } + /// Sets the *ocr* query property to the given value. + /// + /// + /// Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. + pub fn ocr(mut self, new_value: bool) -> FileCopyCall<'a, C, NC, A> { + self._ocr = Some(new_value); + self + } + /// Sets the *convert* query property to the given value. + /// + /// + /// Whether to convert this file to the corresponding Google Docs format. + pub fn convert(mut self, new_value: bool) -> FileCopyCall<'a, C, NC, A> { + self._convert = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileCopyCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileCopyCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileCopyCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Moves a file to the trash. +/// +/// A builder for the *trash* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().trash("fileId") +/// .doit(); +/// # } +/// ``` +pub struct FileTrashCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileTrashCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileTrashCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.trash", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/trash".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to trash. + pub fn file_id(mut self, new_value: &str) -> FileTrashCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileTrashCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileTrashCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileTrashCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Permanently deletes all of the user's trashed files. +/// +/// A builder for the *emptyTrash* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().empty_trash() +/// .doit(); +/// # } +/// ``` +pub struct FileEmptyTrashCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileEmptyTrashCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileEmptyTrashCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.emptyTrash", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((1 + self._additional_params.len())); + for &field in [].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/trash".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileEmptyTrashCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileEmptyTrashCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileEmptyTrashCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the user's files. +/// +/// A builder for the *list* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().list() +/// .q("dolor") +/// .projection("dolor") +/// .page_token("dolor") +/// .max_results(-23) +/// .corpus("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct FileListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _q: Option, + _projection: Option, + _page_token: Option, + _max_results: Option, + _corpus: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, FileList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + if let Some(value) = self._q { + params.push(("q", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._corpus { + params.push(("corpus", value.to_string())); + } + for &field in ["alt", "q", "projection", "pageToken", "maxResults", "corpus"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *q* query property to the given value. + /// + /// + /// Query string for searching files. + pub fn q(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._q = Some(new_value.to_string()); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// This parameter is deprecated and has no function. + pub fn projection(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token for files. + pub fn page_token(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of files to return. + pub fn max_results(mut self, new_value: i32) -> FileListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *corpus* query property to the given value. + /// + /// + /// The body of items (files/documents) to which the query applies. + pub fn corpus(mut self, new_value: &str) -> FileListCall<'a, C, NC, A> { + self._corpus = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Set the file's updated time to the current server time. +/// +/// A builder for the *touch* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().touch("fileId") +/// .doit(); +/// # } +/// ``` +pub struct FileTouchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileTouchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileTouchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.touch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/touch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to update. + pub fn file_id(mut self, new_value: &str) -> FileTouchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileTouchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileTouchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileTouchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates file metadata and/or content. +/// +/// A builder for the *update* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::File; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: File = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().update(&req, "fileId") +/// .use_content_as_indexable_text(false) +/// .update_viewed_date(true) +/// .timed_text_track_name("justo") +/// .timed_text_language("sit") +/// .set_modified_date(true) +/// .remove_parents("diam") +/// .pinned(false) +/// .ocr_language("consetetur") +/// .ocr(true) +/// .new_revision(false) +/// .convert(false) +/// .add_parents("invidunt") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct FileUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: File, + _file_id: String, + _use_content_as_indexable_text: Option, + _update_viewed_date: Option, + _timed_text_track_name: Option, + _timed_text_language: Option, + _set_modified_date: Option, + _remove_parents: Option, + _pinned: Option, + _ocr_language: Option, + _ocr: Option, + _new_revision: Option, + _convert: Option, + _add_parents: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((16 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._use_content_as_indexable_text { + params.push(("useContentAsIndexableText", value.to_string())); + } + if let Some(value) = self._update_viewed_date { + params.push(("updateViewedDate", value.to_string())); + } + if let Some(value) = self._timed_text_track_name { + params.push(("timedTextTrackName", value.to_string())); + } + if let Some(value) = self._timed_text_language { + params.push(("timedTextLanguage", value.to_string())); + } + if let Some(value) = self._set_modified_date { + params.push(("setModifiedDate", value.to_string())); + } + if let Some(value) = self._remove_parents { + params.push(("removeParents", value.to_string())); + } + if let Some(value) = self._pinned { + params.push(("pinned", value.to_string())); + } + if let Some(value) = self._ocr_language { + params.push(("ocrLanguage", value.to_string())); + } + if let Some(value) = self._ocr { + params.push(("ocr", value.to_string())); + } + if let Some(value) = self._new_revision { + params.push(("newRevision", value.to_string())); + } + if let Some(value) = self._convert { + params.push(("convert", value.to_string())); + } + if let Some(value) = self._add_parents { + params.push(("addParents", value.to_string())); + } + for &field in ["alt", "fileId", "useContentAsIndexableText", "updateViewedDate", "timedTextTrackName", "timedTextLanguage", "setModifiedDate", "removeParents", "pinned", "ocrLanguage", "ocr", "newRevision", "convert", "addParents"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/drive/v2/files/{fileId}".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/drive/v2/files/{fileId}".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut mp_reader: MultiPartReader = Default::default(); + let (mut body_reader, content_type) = match protocol { + "simple" => { + mp_reader.reserve_exact(2); + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + mp_reader.add_part(&mut request_value_reader, request_size, json_mime_type.clone()) + .add_part(&mut reader, size, reader_mime_type.clone()); + let mime_type = mp_reader.mime_type(); + (&mut mp_reader as &mut io::Read, ContentType(mime_type)) + }, + _ => (&mut request_value_reader as &mut io::Read, ContentType(json_mime_type.clone())), + }; + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(content_type) + .body(&mut body_reader); + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 5120GB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 5120GB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result<(hyper::client::Response, File)> + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &File) -> FileUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to update. + pub fn file_id(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *use content as indexable text* query property to the given value. + /// + /// + /// Whether to use the content as indexable text. + pub fn use_content_as_indexable_text(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._use_content_as_indexable_text = Some(new_value); + self + } + /// Sets the *update viewed date* query property to the given value. + /// + /// + /// Whether to update the view date after successfully updating the file. + pub fn update_viewed_date(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._update_viewed_date = Some(new_value); + self + } + /// Sets the *timed text track name* query property to the given value. + /// + /// + /// The timed text track name. + pub fn timed_text_track_name(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._timed_text_track_name = Some(new_value.to_string()); + self + } + /// Sets the *timed text language* query property to the given value. + /// + /// + /// The language of the timed text. + pub fn timed_text_language(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._timed_text_language = Some(new_value.to_string()); + self + } + /// Sets the *set modified date* query property to the given value. + /// + /// + /// Whether to set the modified date with the supplied modified date. + pub fn set_modified_date(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._set_modified_date = Some(new_value); + self + } + /// Sets the *remove parents* query property to the given value. + /// + /// + /// Comma-separated list of parent IDs to remove. + pub fn remove_parents(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._remove_parents = Some(new_value.to_string()); + self + } + /// Sets the *pinned* query property to the given value. + /// + /// + /// Whether to pin the new revision. A file can have a maximum of 200 pinned revisions. + pub fn pinned(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._pinned = Some(new_value); + self + } + /// Sets the *ocr language* query property to the given value. + /// + /// + /// If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes. + pub fn ocr_language(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._ocr_language = Some(new_value.to_string()); + self + } + /// Sets the *ocr* query property to the given value. + /// + /// + /// Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. + pub fn ocr(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._ocr = Some(new_value); + self + } + /// Sets the *new revision* query property to the given value. + /// + /// + /// Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If true or not set, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota). + pub fn new_revision(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._new_revision = Some(new_value); + self + } + /// Sets the *convert* query property to the given value. + /// + /// + /// Whether to convert this file to the corresponding Google Docs format. + pub fn convert(mut self, new_value: bool) -> FileUpdateCall<'a, C, NC, A> { + self._convert = Some(new_value); + self + } + /// Sets the *add parents* query property to the given value. + /// + /// + /// Comma-separated list of parent IDs to add. + pub fn add_parents(mut self, new_value: &str) -> FileUpdateCall<'a, C, NC, A> { + self._add_parents = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Permanently deletes a file by ID. Skips the trash. The currently authenticated user must own the file. +/// +/// A builder for the *delete* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().delete("fileId") +/// .doit(); +/// # } +/// ``` +pub struct FileDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to delete. + pub fn file_id(mut self, new_value: &str) -> FileDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates file metadata and/or content. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::File; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: File = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().patch(&req, "fileId") +/// .use_content_as_indexable_text(true) +/// .update_viewed_date(false) +/// .timed_text_track_name("Lorem") +/// .timed_text_language("et") +/// .set_modified_date(true) +/// .remove_parents("consetetur") +/// .pinned(false) +/// .ocr_language("nonumy") +/// .ocr(true) +/// .new_revision(true) +/// .convert(false) +/// .add_parents("At") +/// .doit(); +/// # } +/// ``` +pub struct FilePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: File, + _file_id: String, + _use_content_as_indexable_text: Option, + _update_viewed_date: Option, + _timed_text_track_name: Option, + _timed_text_language: Option, + _set_modified_date: Option, + _remove_parents: Option, + _pinned: Option, + _ocr_language: Option, + _ocr: Option, + _new_revision: Option, + _convert: Option, + _add_parents: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FilePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FilePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((16 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._use_content_as_indexable_text { + params.push(("useContentAsIndexableText", value.to_string())); + } + if let Some(value) = self._update_viewed_date { + params.push(("updateViewedDate", value.to_string())); + } + if let Some(value) = self._timed_text_track_name { + params.push(("timedTextTrackName", value.to_string())); + } + if let Some(value) = self._timed_text_language { + params.push(("timedTextLanguage", value.to_string())); + } + if let Some(value) = self._set_modified_date { + params.push(("setModifiedDate", value.to_string())); + } + if let Some(value) = self._remove_parents { + params.push(("removeParents", value.to_string())); + } + if let Some(value) = self._pinned { + params.push(("pinned", value.to_string())); + } + if let Some(value) = self._ocr_language { + params.push(("ocrLanguage", value.to_string())); + } + if let Some(value) = self._ocr { + params.push(("ocr", value.to_string())); + } + if let Some(value) = self._new_revision { + params.push(("newRevision", value.to_string())); + } + if let Some(value) = self._convert { + params.push(("convert", value.to_string())); + } + if let Some(value) = self._add_parents { + params.push(("addParents", value.to_string())); + } + for &field in ["alt", "fileId", "useContentAsIndexableText", "updateViewedDate", "timedTextTrackName", "timedTextLanguage", "setModifiedDate", "removeParents", "pinned", "ocrLanguage", "ocr", "newRevision", "convert", "addParents"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &File) -> FilePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file to update. + pub fn file_id(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *use content as indexable text* query property to the given value. + /// + /// + /// Whether to use the content as indexable text. + pub fn use_content_as_indexable_text(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._use_content_as_indexable_text = Some(new_value); + self + } + /// Sets the *update viewed date* query property to the given value. + /// + /// + /// Whether to update the view date after successfully updating the file. + pub fn update_viewed_date(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._update_viewed_date = Some(new_value); + self + } + /// Sets the *timed text track name* query property to the given value. + /// + /// + /// The timed text track name. + pub fn timed_text_track_name(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._timed_text_track_name = Some(new_value.to_string()); + self + } + /// Sets the *timed text language* query property to the given value. + /// + /// + /// The language of the timed text. + pub fn timed_text_language(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._timed_text_language = Some(new_value.to_string()); + self + } + /// Sets the *set modified date* query property to the given value. + /// + /// + /// Whether to set the modified date with the supplied modified date. + pub fn set_modified_date(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._set_modified_date = Some(new_value); + self + } + /// Sets the *remove parents* query property to the given value. + /// + /// + /// Comma-separated list of parent IDs to remove. + pub fn remove_parents(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._remove_parents = Some(new_value.to_string()); + self + } + /// Sets the *pinned* query property to the given value. + /// + /// + /// Whether to pin the new revision. A file can have a maximum of 200 pinned revisions. + pub fn pinned(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._pinned = Some(new_value); + self + } + /// Sets the *ocr language* query property to the given value. + /// + /// + /// If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes. + pub fn ocr_language(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._ocr_language = Some(new_value.to_string()); + self + } + /// Sets the *ocr* query property to the given value. + /// + /// + /// Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. + pub fn ocr(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._ocr = Some(new_value); + self + } + /// Sets the *new revision* query property to the given value. + /// + /// + /// Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If true or not set, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota). + pub fn new_revision(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._new_revision = Some(new_value); + self + } + /// Sets the *convert* query property to the given value. + /// + /// + /// Whether to convert this file to the corresponding Google Docs format. + pub fn convert(mut self, new_value: bool) -> FilePatchCall<'a, C, NC, A> { + self._convert = Some(new_value); + self + } + /// Sets the *add parents* query property to the given value. + /// + /// + /// Comma-separated list of parent IDs to add. + pub fn add_parents(mut self, new_value: &str) -> FilePatchCall<'a, C, NC, A> { + self._add_parents = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FilePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FilePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FilePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a file's metadata by ID. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// Please note that due to missing multi-part support on the server side, you will only receive the media, +/// but not the `File` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *get* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.files().get("fileId") +/// .update_viewed_date(true) +/// .projection("ea") +/// .acknowledge_abuse(false) +/// .doit(); +/// # } +/// ``` +pub struct FileGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _update_viewed_date: Option, + _projection: Option, + _acknowledge_abuse: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for FileGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> FileGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, File)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.files.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._update_viewed_date { + params.push(("updateViewedDate", value.to_string())); + } + if let Some(value) = self._projection { + params.push(("projection", value.to_string())); + } + if let Some(value) = self._acknowledge_abuse { + params.push(("acknowledgeAbuse", value.to_string())); + } + for &field in ["fileId", "updateViewedDate", "projection", "acknowledgeAbuse"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + let (json_field_missing, enable_resource_parsing) = { + let mut enable = true; + let mut field_present = true; + for &(name, ref value) in params.iter() { + if name == "alt" { + field_present = false; + if value.as_slice() != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = if enable_resource_parsing { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file in question. + pub fn file_id(mut self, new_value: &str) -> FileGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *update viewed date* query property to the given value. + /// + /// + /// Whether to update the view date after successfully retrieving the file. + pub fn update_viewed_date(mut self, new_value: bool) -> FileGetCall<'a, C, NC, A> { + self._update_viewed_date = Some(new_value); + self + } + /// Sets the *projection* query property to the given value. + /// + /// + /// This parameter is deprecated and has no function. + pub fn projection(mut self, new_value: &str) -> FileGetCall<'a, C, NC, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Sets the *acknowledge abuse* query property to the given value. + /// + /// + /// Whether the user is acknowledging the risk of downloading known malware or other abusive files. + pub fn acknowledge_abuse(mut self, new_value: bool) -> FileGetCall<'a, C, NC, A> { + self._acknowledge_abuse = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets the information about the current user along with Drive API settings +/// +/// A builder for the *get* method supported by a *about* resource. +/// It is not used directly, but through a `AboutMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.about().get() +/// .start_change_id("rebum.") +/// .max_change_id_count(-33) +/// .include_subscribed(true) +/// .doit(); +/// # } +/// ``` +pub struct AboutGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _start_change_id: Option, + _max_change_id_count: Option, + _include_subscribed: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AboutGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AboutGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, About)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.about.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + if let Some(value) = self._start_change_id { + params.push(("startChangeId", value.to_string())); + } + if let Some(value) = self._max_change_id_count { + params.push(("maxChangeIdCount", value.to_string())); + } + if let Some(value) = self._include_subscribed { + params.push(("includeSubscribed", value.to_string())); + } + for &field in ["alt", "startChangeId", "maxChangeIdCount", "includeSubscribed"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/about".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start change id* query property to the given value. + /// + /// + /// Change ID to start counting from when calculating number of remaining change IDs + pub fn start_change_id(mut self, new_value: &str) -> AboutGetCall<'a, C, NC, A> { + self._start_change_id = Some(new_value.to_string()); + self + } + /// Sets the *max change id count* query property to the given value. + /// + /// + /// Maximum number of remaining change IDs to count + pub fn max_change_id_count(mut self, new_value: i64) -> AboutGetCall<'a, C, NC, A> { + self._max_change_id_count = Some(new_value); + self + } + /// Sets the *include subscribed* query property to the given value. + /// + /// + /// When calculating the number of remaining change IDs, whether to include public files the user has opened and shared files. When set to false, this counts only change IDs for owned files and any shared or public files that the user has explicitly added to a folder they own. + pub fn include_subscribed(mut self, new_value: bool) -> AboutGetCall<'a, C, NC, A> { + self._include_subscribed = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AboutGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AboutGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AboutGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Overwrites the Realtime API data model associated with this file with the provided JSON data model. +/// +/// A builder for the *update* method supported by a *realtime* resource. +/// It is not used directly, but through a `RealtimeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.realtime().update("fileId") +/// .base_revision("aliquyam") +/// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// # } +/// ``` +pub struct RealtimeUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _base_revision: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RealtimeUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RealtimeUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + fn doit(mut self, mut reader: RS, reader_mime_type: mime::Mime, protocol: &'static str) -> Result + where RS: ReadSeek { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.realtime.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._base_revision { + params.push(("baseRevision", value.to_string())); + } + for &field in ["fileId", "baseRevision"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = if protocol == "simple" { + "https://www.googleapis.com/upload/drive/v2/files/{fileId}/realtime".to_string() + } else if protocol == "resumable" { + "https://www.googleapis.com/resumable/upload/drive/v2/files/{fileId}/realtime".to_string() + } else { + unreachable!() + }; + params.push(("uploadType", protocol.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + let mut should_ask_dlg_for_url = false; + let mut upload_url_from_server; + let mut upload_url: Option = None; + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + if should_ask_dlg_for_url && (upload_url = dlg.upload_url()) == () && upload_url.is_some() { + should_ask_dlg_for_url = false; + upload_url_from_server = false; + let mut response = hyper::client::Response::new(Box::new(cmn::DummyNetworkStream)); + match response { + Ok(ref mut res) => { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())) + } + _ => unreachable!(), + } + response + } else { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + if protocol == "simple" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + req = req.header(ContentType(reader_mime_type.clone())) + .header(ContentLength(size)) + .body(&mut reader); + } + upload_url_from_server = true; + if protocol == "resumable" { + req = req.header(cmn::XUploadContentType(reader_mime_type.clone())); + } + + dlg.pre_request(); + req.send() + + } + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 0 { + return Result::UploadSizeLimitExceeded(size, 0) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(url); + } + + cmn::ResumableUploadHelper { + client: &mut client.borrow_mut(), + delegate: dlg, + start_at: if upload_url_from_server { Some(0) } else { None }, + auth: &mut *self.hub.auth.borrow_mut(), + user_agent: &self.hub._user_agent, + auth_header: auth_header.clone(), + url: url, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Result::Cancelled + } + Some(Err(err)) => { + dlg.finished(false); + return Result::HttpError(err) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.finished(false); + return Result::Failure(res) + } + } + } + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + /// Upload media all at once. + /// If the upload fails for whichever reason, all progress is lost. + /// + /// * *max size*: 10MB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload(self, stream: RS, mime_type: mime::Mime) -> Result + where RS: ReadSeek { + self.doit(stream, mime_type, "simple") + } + /// Upload media in a resumeable fashion. + /// Even if the upload fails or is interrupted, it can be resumed for a + /// certain amount of time as the server maintains state temporarily. + /// + /// TODO: Write more about how delegation works in this particular case. + /// + /// * *max size*: 10MB + /// * *multipart*: yes + /// * *valid mime types*: '*/*' + pub fn upload_resumable(self, resumeable_stream: RS, mime_type: mime::Mime) -> Result + where RS: ReadSeek { + self.doit(resumeable_stream, mime_type, "resumable") + } + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file that the Realtime API data model is associated with. + pub fn file_id(mut self, new_value: &str) -> RealtimeUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *base revision* query property to the given value. + /// + /// + /// The revision of the model to diff the uploaded model against. If set, the uploaded model is diffed against the provided revision and those differences are merged with any changes made to the model after the provided revision. If not set, the uploaded model replaces the current model on the server. + pub fn base_revision(mut self, new_value: &str) -> RealtimeUpdateCall<'a, C, NC, A> { + self._base_revision = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RealtimeUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RealtimeUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RealtimeUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Exports the contents of the Realtime API data model associated with this file as JSON. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// +/// A builder for the *get* method supported by a *realtime* resource. +/// It is not used directly, but through a `RealtimeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.realtime().get("fileId") +/// .revision(-40) +/// .doit(); +/// # } +/// ``` +pub struct RealtimeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _revision: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RealtimeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RealtimeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.realtime.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._revision { + params.push(("revision", value.to_string())); + } + for &field in ["fileId", "revision"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/realtime".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file that the Realtime API data model is associated with. + pub fn file_id(mut self, new_value: &str) -> RealtimeGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *revision* query property to the given value. + /// + /// + /// The revision of the Realtime API data model to export. Revisions start at 1 (the initial empty data model) and are incremented with each change. If this parameter is excluded, the most recent data model will be returned. + pub fn revision(mut self, new_value: i32) -> RealtimeGetCall<'a, C, NC, A> { + self._revision = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RealtimeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RealtimeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RealtimeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific app. +/// +/// A builder for the *get* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.apps().get("appId") +/// .doit(); +/// # } +/// ``` +pub struct AppGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _app_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AppGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AppGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, App)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.apps.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("appId", self._app_id.to_string())); + for &field in ["alt", "appId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/apps/{appId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{appId}", "appId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["appId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *app id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the app. + pub fn app_id(mut self, new_value: &str) -> AppGetCall<'a, C, NC, A> { + self._app_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AppGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a user's installed apps. +/// +/// A builder for the *list* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.apps().list() +/// .language_code("labore") +/// .app_filter_mime_types("sed") +/// .app_filter_extensions("ea") +/// .doit(); +/// # } +/// ``` +pub struct AppListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _language_code: Option, + _app_filter_mime_types: Option, + _app_filter_extensions: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for AppListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> AppListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AppList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.apps.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + if let Some(value) = self._language_code { + params.push(("languageCode", value.to_string())); + } + if let Some(value) = self._app_filter_mime_types { + params.push(("appFilterMimeTypes", value.to_string())); + } + if let Some(value) = self._app_filter_extensions { + params.push(("appFilterExtensions", value.to_string())); + } + for &field in ["alt", "languageCode", "appFilterMimeTypes", "appFilterExtensions"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/apps".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *language code* query property to the given value. + /// + /// + /// A language or locale code, as defined by BCP 47, with some extensions from Unicode's LDML format (http://www.unicode.org/reports/tr35/). + pub fn language_code(mut self, new_value: &str) -> AppListCall<'a, C, NC, A> { + self._language_code = Some(new_value.to_string()); + self + } + /// Sets the *app filter mime types* query property to the given value. + /// + /// + /// A comma-separated list of MIME types for open with filtering. All apps within the given app query scope which can open any of the given MIME types will be included in the response. If appFilterExtensions are provided as well, the result is a union of the two resulting app lists. + pub fn app_filter_mime_types(mut self, new_value: &str) -> AppListCall<'a, C, NC, A> { + self._app_filter_mime_types = Some(new_value.to_string()); + self + } + /// Sets the *app filter extensions* query property to the given value. + /// + /// + /// A comma-separated list of file extensions for open with filtering. All apps within the given app query scope which can open any of the given file extensions will be included in the response. If appFilterMimeTypes are provided as well, the result is a union of the two resulting app lists. + pub fn app_filter_extensions(mut self, new_value: &str) -> AppListCall<'a, C, NC, A> { + self._app_filter_extensions = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AppListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a comment. +/// +/// A builder for the *delete* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().delete("fileId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["fileId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> CommentDeleteCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a comment by ID. +/// +/// A builder for the *get* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().get("fileId", "commentId") +/// .include_deleted(false) +/// .doit(); +/// # } +/// ``` +pub struct CommentGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _comment_id: String, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "fileId", "commentId", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> CommentGetCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// If set, this will succeed when retrieving a deleted comment, and will include any deleted replies. + pub fn include_deleted(mut self, new_value: bool) -> CommentGetCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new comment on the given file. +/// +/// A builder for the *insert* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Comment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Comment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().insert(&req, "fileId") +/// .doit(); +/// # } +/// ``` +pub struct CommentInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Comment, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Comment) -> CommentInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentInsertCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing comment. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Comment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Comment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().patch(&req, "fileId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Comment, + _file_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "fileId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Comment) -> CommentPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentPatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> CommentPatchCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing comment. +/// +/// A builder for the *update* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Comment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Comment = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().update(&req, "fileId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct CommentUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Comment, + _file_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Comment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "fileId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Comment) -> CommentUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> CommentUpdateCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a file's comments. +/// +/// A builder for the *list* method supported by a *comment* resource. +/// It is not used directly, but through a `CommentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.comments().list("fileId") +/// .updated_min("ut") +/// .page_token("justo") +/// .max_results(-6) +/// .include_deleted(true) +/// .doit(); +/// # } +/// ``` +pub struct CommentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _updated_min: Option, + _page_token: Option, + _max_results: Option, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for CommentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> CommentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.comments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._updated_min { + params.push(("updatedMin", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "fileId", "updatedMin", "pageToken", "maxResults", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *updated min* query property to the given value. + /// + /// + /// Only discussions that were updated after this timestamp will be returned. Formatted as an RFC 3339 timestamp. + pub fn updated_min(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._updated_min = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> CommentListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of discussions to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> CommentListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// If set, all comments and replies, including deleted comments and replies (with content stripped) will be returned. + pub fn include_deleted(mut self, new_value: bool) -> CommentListCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CommentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CommentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CommentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a folder's children. +/// +/// A builder for the *list* method supported by a *children* resource. +/// It is not used directly, but through a `ChildrenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.children().list("folderId") +/// .q("clita") +/// .page_token("diam") +/// .max_results(-71) +/// .doit(); +/// # } +/// ``` +pub struct ChildrenListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _folder_id: String, + _q: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChildrenListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChildrenListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChildList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.children.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("folderId", self._folder_id.to_string())); + if let Some(value) = self._q { + params.push(("q", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "folderId", "q", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{folderId}/children".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{folderId}", "folderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["folderId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *folder id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the folder. + pub fn folder_id(mut self, new_value: &str) -> ChildrenListCall<'a, C, NC, A> { + self._folder_id = new_value.to_string(); + self + } + /// Sets the *q* query property to the given value. + /// + /// + /// Query string for searching children. + pub fn q(mut self, new_value: &str) -> ChildrenListCall<'a, C, NC, A> { + self._q = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token for children. + pub fn page_token(mut self, new_value: &str) -> ChildrenListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of children to return. + pub fn max_results(mut self, new_value: i32) -> ChildrenListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChildrenListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChildrenListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChildrenListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific child reference. +/// +/// A builder for the *get* method supported by a *children* resource. +/// It is not used directly, but through a `ChildrenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.children().get("folderId", "childId") +/// .doit(); +/// # } +/// ``` +pub struct ChildrenGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _folder_id: String, + _child_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChildrenGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChildrenGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChildReference)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.children.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("folderId", self._folder_id.to_string())); + params.push(("childId", self._child_id.to_string())); + for &field in ["alt", "folderId", "childId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{folderId}/children/{childId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{folderId}", "folderId"), ("{childId}", "childId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["folderId", "childId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *folder id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the folder. + pub fn folder_id(mut self, new_value: &str) -> ChildrenGetCall<'a, C, NC, A> { + self._folder_id = new_value.to_string(); + self + } + /// Sets the *child id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the child. + pub fn child_id(mut self, new_value: &str) -> ChildrenGetCall<'a, C, NC, A> { + self._child_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChildrenGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChildrenGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChildrenGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a child from a folder. +/// +/// A builder for the *delete* method supported by a *children* resource. +/// It is not used directly, but through a `ChildrenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.children().delete("folderId", "childId") +/// .doit(); +/// # } +/// ``` +pub struct ChildrenDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _folder_id: String, + _child_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChildrenDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChildrenDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.children.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("folderId", self._folder_id.to_string())); + params.push(("childId", self._child_id.to_string())); + for &field in ["folderId", "childId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{folderId}/children/{childId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{folderId}", "folderId"), ("{childId}", "childId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["folderId", "childId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *folder id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the folder. + pub fn folder_id(mut self, new_value: &str) -> ChildrenDeleteCall<'a, C, NC, A> { + self._folder_id = new_value.to_string(); + self + } + /// Sets the *child id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the child. + pub fn child_id(mut self, new_value: &str) -> ChildrenDeleteCall<'a, C, NC, A> { + self._child_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChildrenDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChildrenDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChildrenDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a file into a folder. +/// +/// A builder for the *insert* method supported by a *children* resource. +/// It is not used directly, but through a `ChildrenMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::ChildReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ChildReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.children().insert(&req, "folderId") +/// .doit(); +/// # } +/// ``` +pub struct ChildrenInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: ChildReference, + _folder_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChildrenInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChildrenInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChildReference)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.children.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("folderId", self._folder_id.to_string())); + for &field in ["alt", "folderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{folderId}/children".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{folderId}", "folderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["folderId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ChildReference) -> ChildrenInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *folder id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the folder. + pub fn folder_id(mut self, new_value: &str) -> ChildrenInsertCall<'a, C, NC, A> { + self._folder_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChildrenInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChildrenInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChildrenInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Stop watching resources through this channel +/// +/// A builder for the *stop* method supported by a *channel* resource. +/// It is not used directly, but through a `ChannelMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.channels().stop(&req) +/// .doit(); +/// # } +/// ``` +pub struct ChannelStopCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Channel, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChannelStopCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChannelStopCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.channels.stop", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + for &field in [].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/channels/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ChannelStopCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChannelStopCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a file's parents. +/// +/// A builder for the *list* method supported by a *parent* resource. +/// It is not used directly, but through a `ParentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.parents().list("fileId") +/// .doit(); +/// # } +/// ``` +pub struct ParentListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ParentListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ParentListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ParentList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.parents.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/parents".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ParentListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ParentListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ParentListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ParentListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a parent from a file. +/// +/// A builder for the *delete* method supported by a *parent* resource. +/// It is not used directly, but through a `ParentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.parents().delete("fileId", "parentId") +/// .doit(); +/// # } +/// ``` +pub struct ParentDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _parent_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ParentDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ParentDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.parents.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("parentId", self._parent_id.to_string())); + for &field in ["fileId", "parentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/parents/{parentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{parentId}", "parentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "parentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ParentDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *parent id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the parent. + pub fn parent_id(mut self, new_value: &str) -> ParentDeleteCall<'a, C, NC, A> { + self._parent_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ParentDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ParentDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ParentDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a parent folder for a file. +/// +/// A builder for the *insert* method supported by a *parent* resource. +/// It is not used directly, but through a `ParentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::ParentReference; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: ParentReference = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.parents().insert(&req, "fileId") +/// .doit(); +/// # } +/// ``` +pub struct ParentInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: ParentReference, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ParentInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ParentInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ParentReference)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.parents.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/parents".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &ParentReference) -> ParentInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ParentInsertCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ParentInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ParentInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ParentInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific parent reference. +/// +/// A builder for the *get* method supported by a *parent* resource. +/// It is not used directly, but through a `ParentMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.parents().get("fileId", "parentId") +/// .doit(); +/// # } +/// ``` +pub struct ParentGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _parent_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ParentGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ParentGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ParentReference)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.parents.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("parentId", self._parent_id.to_string())); + for &field in ["alt", "fileId", "parentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/parents/{parentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{parentId}", "parentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "parentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ParentGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *parent id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the parent. + pub fn parent_id(mut self, new_value: &str) -> ParentGetCall<'a, C, NC, A> { + self._parent_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ParentGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ParentGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ParentGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing reply. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::CommentReply; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CommentReply = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().patch(&req, "fileId", "commentId", "replyId") +/// .doit(); +/// # } +/// ``` +pub struct ReplyPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: CommentReply, + _file_id: String, + _comment_id: String, + _reply_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + params.push(("replyId", self._reply_id.to_string())); + for &field in ["alt", "fileId", "commentId", "replyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies/{replyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId"), ("{replyId}", "replyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["fileId", "commentId", "replyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CommentReply) -> ReplyPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyPatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyPatchCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *reply id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the reply. + pub fn reply_id(mut self, new_value: &str) -> ReplyPatchCall<'a, C, NC, A> { + self._reply_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all of the replies to a comment. +/// +/// A builder for the *list* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().list("fileId", "commentId") +/// .page_token("invidunt") +/// .max_results(-15) +/// .include_deleted(true) +/// .doit(); +/// # } +/// ``` +pub struct ReplyListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _comment_id: String, + _page_token: Option, + _max_results: Option, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentReplyList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "fileId", "commentId", "pageToken", "maxResults", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyListCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. + pub fn page_token(mut self, new_value: &str) -> ReplyListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// The maximum number of replies to include in the response, used for paging. + pub fn max_results(mut self, new_value: i32) -> ReplyListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// If set, all replies, including deleted replies (with content stripped) will be returned. + pub fn include_deleted(mut self, new_value: bool) -> ReplyListCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a reply. +/// +/// A builder for the *get* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().get("fileId", "commentId", "replyId") +/// .include_deleted(false) +/// .doit(); +/// # } +/// ``` +pub struct ReplyGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _comment_id: String, + _reply_id: String, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + params.push(("replyId", self._reply_id.to_string())); + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "fileId", "commentId", "replyId", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies/{replyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId"), ("{replyId}", "replyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["fileId", "commentId", "replyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyGetCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *reply id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the reply. + pub fn reply_id(mut self, new_value: &str) -> ReplyGetCall<'a, C, NC, A> { + self._reply_id = new_value.to_string(); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// If set, this will succeed when retrieving a deleted reply. + pub fn include_deleted(mut self, new_value: bool) -> ReplyGetCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new reply to the given comment. +/// +/// A builder for the *insert* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::CommentReply; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CommentReply = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().insert(&req, "fileId", "commentId") +/// .doit(); +/// # } +/// ``` +pub struct ReplyInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: CommentReply, + _file_id: String, + _comment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + for &field in ["alt", "fileId", "commentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "commentId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CommentReply) -> ReplyInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyInsertCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyInsertCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a reply. +/// +/// A builder for the *delete* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().delete("fileId", "commentId", "replyId") +/// .doit(); +/// # } +/// ``` +pub struct ReplyDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _comment_id: String, + _reply_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + params.push(("replyId", self._reply_id.to_string())); + for &field in ["fileId", "commentId", "replyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies/{replyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId"), ("{replyId}", "replyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["fileId", "commentId", "replyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyDeleteCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *reply id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the reply. + pub fn reply_id(mut self, new_value: &str) -> ReplyDeleteCall<'a, C, NC, A> { + self._reply_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates an existing reply. +/// +/// A builder for the *update* method supported by a *reply* resource. +/// It is not used directly, but through a `ReplyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::CommentReply; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: CommentReply = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.replies().update(&req, "fileId", "commentId", "replyId") +/// .doit(); +/// # } +/// ``` +pub struct ReplyUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: CommentReply, + _file_id: String, + _comment_id: String, + _reply_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ReplyUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ReplyUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CommentReply)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.replies.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("commentId", self._comment_id.to_string())); + params.push(("replyId", self._reply_id.to_string())); + for &field in ["alt", "fileId", "commentId", "replyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/comments/{commentId}/replies/{replyId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{commentId}", "commentId"), ("{replyId}", "replyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["fileId", "commentId", "replyId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &CommentReply) -> ReplyUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> ReplyUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *comment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the comment. + pub fn comment_id(mut self, new_value: &str) -> ReplyUpdateCall<'a, C, NC, A> { + self._comment_id = new_value.to_string(); + self + } + /// Sets the *reply id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the reply. + pub fn reply_id(mut self, new_value: &str) -> ReplyUpdateCall<'a, C, NC, A> { + self._reply_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReplyUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ReplyUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReplyUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a permission from a file. +/// +/// A builder for the *delete* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().delete("fileId", "permissionId") +/// .doit(); +/// # } +/// ``` +pub struct PermissionDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _permission_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("permissionId", self._permission_id.to_string())); + for &field in ["fileId", "permissionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions/{permissionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{permissionId}", "permissionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "permissionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *permission id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the permission. + pub fn permission_id(mut self, new_value: &str) -> PermissionDeleteCall<'a, C, NC, A> { + self._permission_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Inserts a permission for a file. +/// +/// A builder for the *insert* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Permission; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Permission = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().insert(&req, "fileId") +/// .send_notification_emails(true) +/// .email_message("ut") +/// .doit(); +/// # } +/// ``` +pub struct PermissionInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Permission, + _file_id: String, + _send_notification_emails: Option, + _email_message: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Permission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + if let Some(value) = self._send_notification_emails { + params.push(("sendNotificationEmails", value.to_string())); + } + if let Some(value) = self._email_message { + params.push(("emailMessage", value.to_string())); + } + for &field in ["alt", "fileId", "sendNotificationEmails", "emailMessage"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Permission) -> PermissionInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionInsertCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *send notification emails* query property to the given value. + /// + /// + /// Whether to send notification emails when sharing to users or groups. This parameter is ignored and an email is sent if the role is owner. + pub fn send_notification_emails(mut self, new_value: bool) -> PermissionInsertCall<'a, C, NC, A> { + self._send_notification_emails = Some(new_value); + self + } + /// Sets the *email message* query property to the given value. + /// + /// + /// A custom message to include in notification emails. + pub fn email_message(mut self, new_value: &str) -> PermissionInsertCall<'a, C, NC, A> { + self._email_message = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a permission. +/// +/// A builder for the *update* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Permission; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Permission = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().update(&req, "fileId", "permissionId") +/// .transfer_ownership(false) +/// .doit(); +/// # } +/// ``` +pub struct PermissionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Permission, + _file_id: String, + _permission_id: String, + _transfer_ownership: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Permission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("permissionId", self._permission_id.to_string())); + if let Some(value) = self._transfer_ownership { + params.push(("transferOwnership", value.to_string())); + } + for &field in ["alt", "fileId", "permissionId", "transferOwnership"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions/{permissionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{permissionId}", "permissionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "permissionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Permission) -> PermissionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *permission id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the permission. + pub fn permission_id(mut self, new_value: &str) -> PermissionUpdateCall<'a, C, NC, A> { + self._permission_id = new_value.to_string(); + self + } + /// Sets the *transfer ownership* query property to the given value. + /// + /// + /// Whether changing a role to 'owner' downgrades the current owners to writers. Does nothing if the specified role is not 'owner'. + pub fn transfer_ownership(mut self, new_value: bool) -> PermissionUpdateCall<'a, C, NC, A> { + self._transfer_ownership = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a permission. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Permission; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Permission = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().patch(&req, "fileId", "permissionId") +/// .transfer_ownership(true) +/// .doit(); +/// # } +/// ``` +pub struct PermissionPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Permission, + _file_id: String, + _permission_id: String, + _transfer_ownership: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Permission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("permissionId", self._permission_id.to_string())); + if let Some(value) = self._transfer_ownership { + params.push(("transferOwnership", value.to_string())); + } + for &field in ["alt", "fileId", "permissionId", "transferOwnership"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions/{permissionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{permissionId}", "permissionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "permissionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Permission) -> PermissionPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionPatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *permission id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the permission. + pub fn permission_id(mut self, new_value: &str) -> PermissionPatchCall<'a, C, NC, A> { + self._permission_id = new_value.to_string(); + self + } + /// Sets the *transfer ownership* query property to the given value. + /// + /// + /// Whether changing a role to 'owner' downgrades the current owners to writers. Does nothing if the specified role is not 'owner'. + pub fn transfer_ownership(mut self, new_value: bool) -> PermissionPatchCall<'a, C, NC, A> { + self._transfer_ownership = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a file's permissions. +/// +/// A builder for the *list* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().list("fileId") +/// .doit(); +/// # } +/// ``` +pub struct PermissionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PermissionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a permission by ID. +/// +/// A builder for the *get* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().get("fileId", "permissionId") +/// .doit(); +/// # } +/// ``` +pub struct PermissionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _permission_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Permission)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("permissionId", self._permission_id.to_string())); + for &field in ["alt", "fileId", "permissionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/permissions/{permissionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{permissionId}", "permissionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "permissionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> PermissionGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *permission id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the permission. + pub fn permission_id(mut self, new_value: &str) -> PermissionGetCall<'a, C, NC, A> { + self._permission_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns the permission ID for an email address. +/// +/// A builder for the *getIdForEmail* method supported by a *permission* resource. +/// It is not used directly, but through a `PermissionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.permissions().get_id_for_email("email") +/// .doit(); +/// # } +/// ``` +pub struct PermissionGetIdForEmailCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _email: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PermissionGetIdForEmailCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PermissionGetIdForEmailCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PermissionId)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.permissions.getIdForEmail", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("email", self._email.to_string())); + for &field in ["alt", "email"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/permissionIds/{email}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{email}", "email")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["email"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *email* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The email address for which to return a permission ID + pub fn email(mut self, new_value: &str) -> PermissionGetIdForEmailCall<'a, C, NC, A> { + self._email = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PermissionGetIdForEmailCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PermissionGetIdForEmailCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PermissionGetIdForEmailCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Subscribe to changes for a user. +/// +/// A builder for the *watch* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Channel; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Channel = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().watch(&req) +/// .start_change_id("et") +/// .page_token("et") +/// .max_results(-26) +/// .include_subscribed(true) +/// .include_deleted(true) +/// .doit(); +/// # } +/// ``` +pub struct ChangeWatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Channel, + _start_change_id: Option, + _page_token: Option, + _max_results: Option, + _include_subscribed: Option, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeWatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeWatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.changes.watch", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if let Some(value) = self._start_change_id { + params.push(("startChangeId", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_subscribed { + params.push(("includeSubscribed", value.to_string())); + } + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "startChangeId", "pageToken", "maxResults", "includeSubscribed", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/changes/watch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Channel) -> ChangeWatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *start change id* query property to the given value. + /// + /// + /// Change ID to start listing changes from. + pub fn start_change_id(mut self, new_value: &str) -> ChangeWatchCall<'a, C, NC, A> { + self._start_change_id = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token for changes. + pub fn page_token(mut self, new_value: &str) -> ChangeWatchCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of changes to return. + pub fn max_results(mut self, new_value: i32) -> ChangeWatchCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include subscribed* query property to the given value. + /// + /// + /// Whether to include public files the user has opened and shared files. When set to false, the list only includes owned files plus any shared or public files the user has explicitly added to a folder they own. + pub fn include_subscribed(mut self, new_value: bool) -> ChangeWatchCall<'a, C, NC, A> { + self._include_subscribed = Some(new_value); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// Whether to include deleted items. + pub fn include_deleted(mut self, new_value: bool) -> ChangeWatchCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeWatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeWatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeWatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists the changes for a user. +/// +/// A builder for the *list* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().list() +/// .start_change_id("et") +/// .page_token("ipsum") +/// .max_results(-20) +/// .include_subscribed(true) +/// .include_deleted(true) +/// .doit(); +/// # } +/// ``` +pub struct ChangeListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _start_change_id: Option, + _page_token: Option, + _max_results: Option, + _include_subscribed: Option, + _include_deleted: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ChangeList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.changes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + if let Some(value) = self._start_change_id { + params.push(("startChangeId", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._include_subscribed { + params.push(("includeSubscribed", value.to_string())); + } + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + for &field in ["alt", "startChangeId", "pageToken", "maxResults", "includeSubscribed", "includeDeleted"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/changes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *start change id* query property to the given value. + /// + /// + /// Change ID to start listing changes from. + pub fn start_change_id(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._start_change_id = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// Page token for changes. + pub fn page_token(mut self, new_value: &str) -> ChangeListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *max results* query property to the given value. + /// + /// + /// Maximum number of changes to return. + pub fn max_results(mut self, new_value: i32) -> ChangeListCall<'a, C, NC, A> { + self._max_results = Some(new_value); + self + } + /// Sets the *include subscribed* query property to the given value. + /// + /// + /// Whether to include public files the user has opened and shared files. When set to false, the list only includes owned files plus any shared or public files the user has explicitly added to a folder they own. + pub fn include_subscribed(mut self, new_value: bool) -> ChangeListCall<'a, C, NC, A> { + self._include_subscribed = Some(new_value); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// Whether to include deleted items. + pub fn include_deleted(mut self, new_value: bool) -> ChangeListCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific change. +/// +/// A builder for the *get* method supported by a *change* resource. +/// It is not used directly, but through a `ChangeMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.changes().get("changeId") +/// .doit(); +/// # } +/// ``` +pub struct ChangeGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _change_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for ChangeGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> ChangeGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Change)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.changes.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("changeId", self._change_id.to_string())); + for &field in ["alt", "changeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/changes/{changeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{changeId}", "changeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["changeId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *change id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the change. + pub fn change_id(mut self, new_value: &str) -> ChangeGetCall<'a, C, NC, A> { + self._change_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ChangeGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ChangeGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a property. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Property; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Property = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().patch(&req, "fileId", "propertyKey") +/// .visibility("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct PropertyPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Property, + _file_id: String, + _property_key: String, + _visibility: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Property)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("propertyKey", self._property_key.to_string())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + for &field in ["alt", "fileId", "propertyKey", "visibility"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties/{propertyKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{propertyKey}", "propertyKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "propertyKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Property) -> PropertyPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyPatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *property key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key of the property. + pub fn property_key(mut self, new_value: &str) -> PropertyPatchCall<'a, C, NC, A> { + self._property_key = new_value.to_string(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the property. + pub fn visibility(mut self, new_value: &str) -> PropertyPatchCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a property. +/// +/// A builder for the *delete* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().delete("fileId", "propertyKey") +/// .visibility("no") +/// .doit(); +/// # } +/// ``` +pub struct PropertyDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _property_key: String, + _visibility: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("propertyKey", self._property_key.to_string())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + for &field in ["fileId", "propertyKey", "visibility"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties/{propertyKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{propertyKey}", "propertyKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "propertyKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *property key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key of the property. + pub fn property_key(mut self, new_value: &str) -> PropertyDeleteCall<'a, C, NC, A> { + self._property_key = new_value.to_string(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the property. + pub fn visibility(mut self, new_value: &str) -> PropertyDeleteCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds a property to a file. +/// +/// A builder for the *insert* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Property; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Property = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().insert(&req, "fileId") +/// .doit(); +/// # } +/// ``` +pub struct PropertyInsertCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Property, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyInsertCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyInsertCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Property)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Property) -> PropertyInsertCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyInsertCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyInsertCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyInsertCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyInsertCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a file's properties. +/// +/// A builder for the *list* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().list("fileId") +/// .doit(); +/// # } +/// ``` +pub struct PropertyListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PropertyList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a property. +/// +/// A builder for the *update* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Property; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Property = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().update(&req, "fileId", "propertyKey") +/// .visibility("elitr") +/// .doit(); +/// # } +/// ``` +pub struct PropertyUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Property, + _file_id: String, + _property_key: String, + _visibility: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Property)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("propertyKey", self._property_key.to_string())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + for &field in ["alt", "fileId", "propertyKey", "visibility"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties/{propertyKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{propertyKey}", "propertyKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "propertyKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Property) -> PropertyUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *property key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key of the property. + pub fn property_key(mut self, new_value: &str) -> PropertyUpdateCall<'a, C, NC, A> { + self._property_key = new_value.to_string(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the property. + pub fn visibility(mut self, new_value: &str) -> PropertyUpdateCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a property by its key. +/// +/// A builder for the *get* method supported by a *property* resource. +/// It is not used directly, but through a `PropertyMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.properties().get("fileId", "propertyKey") +/// .visibility("elitr") +/// .doit(); +/// # } +/// ``` +pub struct PropertyGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _property_key: String, + _visibility: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for PropertyGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> PropertyGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Property)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.properties.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("propertyKey", self._property_key.to_string())); + if let Some(value) = self._visibility { + params.push(("visibility", value.to_string())); + } + for &field in ["alt", "fileId", "propertyKey", "visibility"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/properties/{propertyKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{propertyKey}", "propertyKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "propertyKey"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> PropertyGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *property key* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The key of the property. + pub fn property_key(mut self, new_value: &str) -> PropertyGetCall<'a, C, NC, A> { + self._property_key = new_value.to_string(); + self + } + /// Sets the *visibility* query property to the given value. + /// + /// + /// The visibility of the property. + pub fn visibility(mut self, new_value: &str) -> PropertyGetCall<'a, C, NC, A> { + self._visibility = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PropertyGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PropertyGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PropertyGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Gets a specific revision. +/// +/// A builder for the *get* method supported by a *revision* resource. +/// It is not used directly, but through a `RevisionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.revisions().get("fileId", "revisionId") +/// .doit(); +/// # } +/// ``` +pub struct RevisionGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _revision_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RevisionGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Revision)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.revisions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("revisionId", self._revision_id.to_string())); + for &field in ["alt", "fileId", "revisionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/revisions/{revisionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{revisionId}", "revisionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "revisionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> RevisionGetCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *revision id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the revision. + pub fn revision_id(mut self, new_value: &str) -> RevisionGetCall<'a, C, NC, A> { + self._revision_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RevisionGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RevisionGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Removes a revision. +/// +/// A builder for the *delete* method supported by a *revision* resource. +/// It is not used directly, but through a `RevisionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.revisions().delete("fileId", "revisionId") +/// .doit(); +/// # } +/// ``` +pub struct RevisionDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _revision_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RevisionDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.revisions.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("revisionId", self._revision_id.to_string())); + for &field in ["fileId", "revisionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/revisions/{revisionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{revisionId}", "revisionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "revisionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> RevisionDeleteCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *revision id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the revision. + pub fn revision_id(mut self, new_value: &str) -> RevisionDeleteCall<'a, C, NC, A> { + self._revision_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RevisionDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RevisionDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a revision. +/// +/// A builder for the *update* method supported by a *revision* resource. +/// It is not used directly, but through a `RevisionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Revision; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Revision = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.revisions().update(&req, "fileId", "revisionId") +/// .doit(); +/// # } +/// ``` +pub struct RevisionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Revision, + _file_id: String, + _revision_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RevisionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Revision)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.revisions.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("revisionId", self._revision_id.to_string())); + for &field in ["alt", "fileId", "revisionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/revisions/{revisionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{revisionId}", "revisionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "revisionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Revision) -> RevisionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> RevisionUpdateCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *revision id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the revision. + pub fn revision_id(mut self, new_value: &str) -> RevisionUpdateCall<'a, C, NC, A> { + self._revision_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RevisionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RevisionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists a file's revisions. +/// +/// A builder for the *list* method supported by a *revision* resource. +/// It is not used directly, but through a `RevisionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.revisions().list("fileId") +/// .doit(); +/// # } +/// ``` +pub struct RevisionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _file_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RevisionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RevisionList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.revisions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + for &field in ["alt", "fileId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/revisions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AppReadonly.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["fileId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the file. + pub fn file_id(mut self, new_value: &str) -> RevisionListCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RevisionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RevisionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a revision. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *revision* resource. +/// It is not used directly, but through a `RevisionMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-drive2" as drive2; +/// use drive2::Revision; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use drive2::Drive; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Drive::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Revision = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.revisions().patch(&req, "fileId", "revisionId") +/// .doit(); +/// # } +/// ``` +pub struct RevisionPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Drive, + _request: Revision, + _file_id: String, + _revision_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for RevisionPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> RevisionPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Revision)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "drive.revisions.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("fileId", self._file_id.to_string())); + params.push(("revisionId", self._revision_id.to_string())); + for &field in ["alt", "fileId", "revisionId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/drive/v2/files/{fileId}/revisions/{revisionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{fileId}", "fileId"), ("{revisionId}", "revisionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["fileId", "revisionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Revision) -> RevisionPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *file id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the file. + pub fn file_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, NC, A> { + self._file_id = new_value.to_string(); + self + } + /// Sets the *revision id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID for the revision. + pub fn revision_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, NC, A> { + self._revision_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RevisionPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RevisionPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/fitness1/Cargo.toml b/gen/fitness1/Cargo.toml new file mode 100644 index 0000000000..25ccf1dcda --- /dev/null +++ b/gen/fitness1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-fitness1" +version = "0.1.0+20150222" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with fitness (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/fitness1" +homepage = "https://developers.google.com/fit/rest/" +documentation = "http://byron.github.io/google-apis-rs/google-fitness1" +license = "MIT" +keywords = ["fitness", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/fitness1/LICENSE.md b/gen/fitness1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/fitness1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/fitness1/README.md b/gen/fitness1/README.md new file mode 100644 index 0000000000..a0706f5831 --- /dev/null +++ b/gen/fitness1/README.md @@ -0,0 +1,172 @@ + +The `google-fitness1` library allows access to all features of the *Google fitness* service. + +This documentation was generated from *fitness* crate version *0.1.0+20150222*, where *20150222* is the exact revision of the *fitness:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *fitness* *v1* API can be found at the +[official documentation site](https://developers.google.com/fit/rest/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-fitness1/struct.Fitness.html) ... + +* users + * [*data sources create*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceCreateCall.html), [*data sources datasets delete*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceDatasetDeleteCall.html), [*data sources datasets get*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceDatasetGetCall.html), [*data sources datasets patch*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceDatasetPatchCall.html), [*data sources get*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceGetCall.html), [*data sources list*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceListCall.html), [*data sources patch*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourcePatchCall.html), [*data sources update*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserDataSourceUpdateCall.html), [*sessions delete*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserSessionDeleteCall.html), [*sessions list*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserSessionListCall.html) and [*sessions update*](http://byron.github.io/google-apis-rs/google-fitness1/struct.UserSessionUpdateCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-fitness1/struct.Fitness.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-fitness1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-fitness1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-fitness1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.users().data_sources_get(...).doit() +let r = hub.users().data_sources_update(...).doit() +let r = hub.users().data_sources_create(...).doit() +let r = hub.users().data_sources_patch(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-fitness1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-fitness1" as fitness1; +use fitness1::DataSource; +use fitness1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use fitness1::Fitness; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Fitness::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req: DataSource = Default::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.users().data_sources_update(&req, "userId", "dataSourceId") + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-fitness1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-fitness1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-fitness1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-fitness1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-fitness1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-fitness1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-fitness1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-fitness1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-fitness1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-fitness1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-fitness1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-fitness1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-fitness1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **fitness1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/fitness1/src/cmn.rs b/gen/fitness1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/fitness1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/fitness1/src/lib.rs b/gen/fitness1/src/lib.rs new file mode 100644 index 0000000000..e6d968aa84 --- /dev/null +++ b/gen/fitness1/src/lib.rs @@ -0,0 +1,3832 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *fitness* crate version *0.1.0+20150222*, where *20150222* is the exact revision of the *fitness:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *fitness* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/fit/rest/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/fitness1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Fitness.html) ... +//! +//! * users +//! * [*data sources create*](struct.UserDataSourceCreateCall.html), [*data sources datasets delete*](struct.UserDataSourceDatasetDeleteCall.html), [*data sources datasets get*](struct.UserDataSourceDatasetGetCall.html), [*data sources datasets patch*](struct.UserDataSourceDatasetPatchCall.html), [*data sources get*](struct.UserDataSourceGetCall.html), [*data sources list*](struct.UserDataSourceListCall.html), [*data sources patch*](struct.UserDataSourcePatchCall.html), [*data sources update*](struct.UserDataSourceUpdateCall.html), [*sessions delete*](struct.UserSessionDeleteCall.html), [*sessions list*](struct.UserSessionListCall.html) and [*sessions update*](struct.UserSessionUpdateCall.html) +//! +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Fitness.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.users().data_sources_get(...).doit() +//! let r = hub.users().data_sources_update(...).doit() +//! let r = hub.users().data_sources_create(...).doit() +//! let r = hub.users().data_sources_patch(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-fitness1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-fitness1" as fitness1; +//! use fitness1::DataSource; +//! use fitness1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use fitness1::Fitness; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Fitness::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req: DataSource = Default::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.users().data_sources_update(&req, "userId", "dataSourceId") +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// View body sensor information in Google Fit + BodyRead, + + /// View and store body sensor data in Google Fit + BodyWrite, + + /// View and store your location data in Google Fit + LocationWrite, + + /// View your stored location data in Google Fit + LocationRead, + + /// View your activity information in Google Fit + ActivityRead, + + /// View and store your activity information in Google Fit + ActivityWrite, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::BodyRead => "https://www.googleapis.com/auth/fitness.body.read", + Scope::BodyWrite => "https://www.googleapis.com/auth/fitness.body.write", + Scope::LocationWrite => "https://www.googleapis.com/auth/fitness.location.write", + Scope::LocationRead => "https://www.googleapis.com/auth/fitness.location.read", + Scope::ActivityRead => "https://www.googleapis.com/auth/fitness.activity.read", + Scope::ActivityWrite => "https://www.googleapis.com/auth/fitness.activity.write", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::BodyRead + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Fitness related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-fitness1" as fitness1; +/// use fitness1::DataSource; +/// use fitness1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use fitness1::Fitness; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DataSource = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_update(&req, "userId", "dataSourceId") +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Fitness { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Fitness {} + +impl<'a, C, NC, A> Fitness + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Fitness { + Fitness { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn users(&'a self) -> UserMethods<'a, C, NC, A> { + UserMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// See: google3/java/com/google/android/apps/heart/platform/api/DataType.java +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DataType { + /// A field represents one dimension of a data type. + pub field: Vec, + /// Each data type has a unique, namespaced, name. All data types in the com.google namespace are shared as part of the platform. + pub name: String, +} + +impl Part for DataType {} + + +/// Holder object for the value of a single field in a data point. +/// +/// A field value has a particular format and is only ever set to one of an integer or a floating point value. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Value { + /// Floating point value. When this is set, intVal must not be set. + #[serde(alias="fpVal")] + pub fp_val: f64, + /// Integer value. When this is set, fpVal must not be set. + #[serde(alias="intVal")] + pub int_val: i32, +} + +impl Part for Value {} + + +/// A dataset represents a projection container for data points. They do not carry any info of their own. Datasets represent a set of data points from a particular data source. A data point can be found in more than one dataset. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [data sources datasets patch users](struct.UserDataSourceDatasetPatchCall.html) (request|response) +/// * [data sources datasets get users](struct.UserDataSourceDatasetGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Dataset { + /// The smallest start time of all data points in this possibly partial representation of the dataset. Time is in nanoseconds from epoch. This should also match the first part of the dataset identifier. + #[serde(alias="minStartTimeNs")] + pub min_start_time_ns: Option, + /// This token will be set when a dataset is received in response to a GET request and the dataset is too large to be included in a single response. Provide this value in a subsequent GET request to return the next page of data points within this dataset. + #[serde(alias="nextPageToken")] + pub next_page_token: Option, + /// The largest end time of all data points in this possibly partial representation of the dataset. Time is in nanoseconds from epoch. This should also match the first part of the dataset identifier. + #[serde(alias="maxEndTimeNs")] + pub max_end_time_ns: Option, + /// The data stream ID of the data source that created the points in this dataset. + #[serde(alias="dataSourceId")] + pub data_source_id: Option, + /// A partial list of data points contained in the dataset, ordered by largest endTimeNanos first. This list is considered complete when retrieving a small dataset and partial when patching a dataset or retrieving a dataset that is too large to include in a single response. + pub point: Option>, +} + +impl RequestValue for Dataset {} +impl ResponseResult for Dataset {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [data sources list users](struct.UserDataSourceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListDataSourcesResponse { + /// A previously created data source. + #[serde(alias="dataSource")] + pub data_source: Vec, +} + +impl ResponseResult for ListDataSourcesResponse {} + + +/// See: google3/java/com/google/android/apps/heart/platform/api/Application.java +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Application { + /// Package name for this application. This is used as a unique identifier when created by Android applications, but cannot be specified by REST clients. REST clients will have their developer project number reflected into the Data Source data stream IDs, instead of the packageName. + #[serde(alias="packageName")] + pub package_name: String, + /// Version of the application. You should update this field whenever the application changes in a way that affects the computation of the data. + pub version: String, + /// The name of this application. This is required for REST clients, but we do not enforce uniqueness of this name. It is provided as a matter of convenience for other developers who would like to identify which REST created an Application or Data Source. + pub name: String, + /// An optional URI that can be used to link back to the application. + #[serde(alias="detailsUrl")] + pub details_url: String, +} + +impl Part for Application {} + + +/// Sessions contain metadata, such as a user-friendly name and time interval information. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [sessions update users](struct.UserSessionUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Session { + /// A timestamp that indicates when the session was last modified. + #[serde(alias="modifiedTimeMillis")] + pub modified_time_millis: Option, + /// An end time, in milliseconds since epoch, inclusive. + #[serde(alias="endTimeMillis")] + pub end_time_millis: Option, + /// A description for this session. + pub description: Option, + /// The type of activity this session represents. + #[serde(alias="activityType")] + pub activity_type: Option, + /// The application that created the session. + pub application: Option, + /// A start time, in milliseconds since epoch, inclusive. + #[serde(alias="startTimeMillis")] + pub start_time_millis: Option, + /// A client-generated identifier that is unique across all sessions owned by this particular user. + pub id: Option, + /// A human readable name of the session. + pub name: Option, +} + +impl RequestValue for Session {} +impl ResponseResult for Session {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [sessions list users](struct.UserSessionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ListSessionsResponse { + /// The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// If includeDeleted is set to true in the request, this list will contain sessions deleted with original end times that are within the startTime and endTime frame. + #[serde(alias="deletedSession")] + pub deleted_session: Vec, + /// Sessions with an end time that is between startTime and endTime of the request. + pub session: Vec, +} + +impl ResponseResult for ListSessionsResponse {} + + +/// Representation of an integrated device (such as a phone or a wearable) that can hold sensors. Each sensor is exposed as a data source. +/// +/// The main purpose of the device information contained in this class is to identify the hardware of a particular data source. This can be useful in different ways, including: +/// - Distinguishing two similar sensors on different devices (the step counter on two nexus 5 phones, for instance) +/// - Display the source of data to the user (by using the device make / model) +/// - Treat data differently depending on sensor type (accelerometers on a watch may give different patterns than those on a phone) +/// - Build different analysis models for each device/version. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Device { + /// End-user visible model name for the device. + pub model: String, + /// Version string for the device hardware/software. + pub version: String, + /// A constant representing the type of the device. + #[serde(alias="type")] + pub type_: String, + /// The serial number or other unique ID for the hardware. This field is obfuscated when read by any REST or Android client that did not create the data source. Only the data source creator will see the uid field in clear and normal form. + pub uid: String, + /// Manufacturer of the product/hardware. + pub manufacturer: String, +} + +impl Part for Device {} + + +/// In case of multi-dimensional data (such as an accelerometer with x, y, and z axes) each field represents one dimension. Each data type field has a unique name which identifies it. The field also defines the format of the data (int, float, etc.). +/// +/// This message is only instantiated in code and not used for wire comms or stored in any way. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DataTypeField { + /// no description provided + pub optional: bool, + /// Defines the name and format of data. Unlike data type names, field names are not namespaced, and only need to be unique within the data type. + pub name: String, + /// The different supported formats for each field in a data type. + pub format: String, +} + +impl Part for DataTypeField {} + + +/// Represents a single data point, generated by a particular data source. A data point holds a value for each field, an end timestamp and an optional start time. The exact semantics of each of these attributes are specified in the documentation for the particular data type. +/// +/// A data point can represent an instantaneous measurement, reading or input observation, as well as averages or aggregates over a time interval. Check the data type documentation to determine which is the case for a particular data type. +/// +/// Data points always contain one value for each field of the data type. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DataPoint { + /// Used for version checking during transformation; that is, a datapoint can only replace another datapoint that has an older computation time stamp. + #[serde(alias="computationTimeMillis")] + pub computation_time_millis: String, + /// Indicates the last time this data point was modified. Useful only in contexts where we are listing the data changes, rather than representing the current state of the data. + #[serde(alias="modifiedTimeMillis")] + pub modified_time_millis: String, + /// The start time of the interval represented by this data point, in nanoseconds since epoch. + #[serde(alias="startTimeNanos")] + pub start_time_nanos: String, + /// The data type defining the format of the values in this data point. + #[serde(alias="dataTypeName")] + pub data_type_name: String, + /// Values of each data type field for the data point. It is expected that each value corresponding to a data type field will occur in the same order that the field is listed with in the data type specified in a data source. + /// + /// Only one of integer and floating point fields will be populated, depending on the format enum value within data source's type field. + pub value: Vec, + /// The end time of the interval represented by this data point, in nanoseconds since epoch. + #[serde(alias="endTimeNanos")] + pub end_time_nanos: String, + /// If the data point is contained in a dataset for a derived data source, this field will be populated with the data source stream ID that created the data point originally. + #[serde(alias="originDataSourceId")] + pub origin_data_source_id: String, + /// The raw timestamp from the original SensorEvent. + #[serde(alias="rawTimestampNanos")] + pub raw_timestamp_nanos: String, +} + +impl Part for DataPoint {} + + +/// Definition of a unique source of sensor data. Data sources can expose raw data coming from hardware sensors on local or companion devices. They can also expose derived data, created by transforming or merging other data sources. Multiple data sources can exist for the same data type. Every data point inserted into or read from this service has an associated data source. +/// +/// The data source contains enough information to uniquely identify its data, including the hardware device and the application that collected and/or transformed the data. It also holds useful metadata, such as the hardware and application versions, and the device type. +/// +/// Each data source produces a unique stream of data, with a unique identifier. Not all changes to data source affect the stream identifier, so that data collected by updated versions of the same application/device can still be considered to belong to the same data stream. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [data sources get users](struct.UserDataSourceGetCall.html) (response) +/// * [data sources update users](struct.UserDataSourceUpdateCall.html) (request|response) +/// * [data sources create users](struct.UserDataSourceCreateCall.html) (request|response) +/// * [data sources patch users](struct.UserDataSourcePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DataSource { + /// Information about an application which feeds sensor data into the platform. + pub application: Option, + /// Representation of an integrated device (such as a phone or a wearable) that can hold sensors. + pub device: Option, + /// An end-user visible name for this data source. + pub name: Option, + /// The stream name uniquely identifies this particular data source among other data sources of the same type from the same underlying producer. Setting the stream name is optional, but should be done whenever an application exposes two streams for the same data type, or when a device has two equivalent sensors. + #[serde(alias="dataStreamName")] + pub data_stream_name: Option, + /// The data type defines the schema for a stream of data being collected by, inserted into, or queried from the Fitness API. + #[serde(alias="dataType")] + pub data_type: Option, + /// A unique identifier for the data stream produced by this data source. The identifier includes: + /// + /// + /// - The physical device's manufacturer, model, and serial number (UID). + /// - The application's package name or name. Package name is used when the data source was created by an Android application. The developer project number is used when the data source was created by a REST client. + /// - The data source's type. + /// - The data source's stream name. Note that not all attributes of the data source are used as part of the stream identifier. In particular, the version of the hardware/the application isn't used. This allows us to preserve the same stream through version updates. This also means that two DataSource objects may represent the same data stream even if they're not equal. + /// + /// The exact format of the data stream ID created by an Android application is: type:dataType.name:application.packageName:device.manufacturer:device.model:device.uid:dataStreamName + /// + /// The exact format of the data stream ID created by a REST client is: type:dataType.name:developer project number:device.manufacturer:device.model:device.uid:dataStreamName + /// + /// When any of the optional fields that comprise of the data stream ID are blank, they will be omitted from the data stream ID. The minnimum viable data stream ID would be: type:dataType.name:developer project number + /// + /// Finally, the developer project number is obfuscated when read by any REST or Android client that did not create the data source. Only the data source creator will see the developer project number in clear and normal form. + #[serde(alias="dataStreamId")] + pub data_stream_id: Option, + /// A constant describing the type of this data source. Indicates whether this data source produces raw or derived data. + #[serde(alias="type")] + pub type_: Option, +} + +impl RequestValue for DataSource {} +impl ResponseResult for DataSource {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *user* resources. +/// It is not used directly, but through the `Fitness` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-fitness1" as fitness1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use fitness1::Fitness; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `data_sources_create(...)`, `data_sources_datasets_delete(...)`, `data_sources_datasets_get(...)`, `data_sources_datasets_patch(...)`, `data_sources_get(...)`, `data_sources_list(...)`, `data_sources_patch(...)`, `data_sources_update(...)`, `sessions_delete(...)`, `sessions_list(...)` and `sessions_update(...)` +/// // to build up your call. +/// let rb = hub.users(); +/// # } +/// ``` +pub struct UserMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for UserMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a dataset containing all data points whose start and end times overlap with the specified range of the dataset minimum start time and maximum end time. Specifically, any data point whose start time is less than or equal to the dataset end time and whose end time is greater than or equal to the dataset start time. + pub fn data_sources_datasets_get(&self, user_id: &str, data_source_id: &str, dataset_id: &str) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + UserDataSourceDatasetGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _dataset_id: dataset_id.to_string(), + _page_token: Default::default(), + _limit: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a new data source that is unique across all data sources belonging to this user. The data stream ID field can be omitted and will be generated by the server with the correct format. The data stream ID is an ordered combination of some fields from the data source. In addition to the data source fields reflected into the data source ID, the developer project number that is authenticated when creating the data source is included. This developer project number is obfuscated when read by any other developer reading public data types. + pub fn data_sources_create(&self, request: &DataSource, user_id: &str) -> UserDataSourceCreateCall<'a, C, NC, A> { + UserDataSourceCreateCall { + hub: self.hub, + _request: request.clone(), + _user_id: user_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Performs an inclusive delete of all data points whose start and end times have any overlap with the time range specified by the dataset ID. For most data types, the entire data point will be deleted. For data types where the time span represents a consistent value (such as com.google.activity.segment), and a data point straddles either end point of the dataset, only the overlapping portion of the data point will be deleted. + pub fn data_sources_datasets_delete(&self, user_id: &str, data_source_id: &str, dataset_id: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + UserDataSourceDatasetDeleteCall { + hub: self.hub, + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _dataset_id: dataset_id.to_string(), + _modified_time_millis: Default::default(), + _current_time_millis: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds data points to a dataset. The dataset need not be previously created. All points within the given dataset will be returned with subsquent calls to retrieve this dataset. Data points can belong to more than one dataset. This method does not use patch semantics. + pub fn data_sources_datasets_patch(&self, request: &Dataset, user_id: &str, data_source_id: &str, dataset_id: &str) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + UserDataSourceDatasetPatchCall { + hub: self.hub, + _request: request.clone(), + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _dataset_id: dataset_id.to_string(), + _current_time_millis: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a session specified by the given session ID. + pub fn sessions_delete(&self, user_id: &str, session_id: &str) -> UserSessionDeleteCall<'a, C, NC, A> { + UserSessionDeleteCall { + hub: self.hub, + _user_id: user_id.to_string(), + _session_id: session_id.to_string(), + _current_time_millis: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a data source identified by a data stream ID. + pub fn data_sources_get(&self, user_id: &str, data_source_id: &str) -> UserDataSourceGetCall<'a, C, NC, A> { + UserDataSourceGetCall { + hub: self.hub, + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a given data source. It is an error to modify the data source's data stream ID, data type, type, stream name or device information apart from the device version. Changing these fields would require a new unique data stream ID and separate data source. + /// + /// Data sources are identified by their data stream ID. + pub fn data_sources_update(&self, request: &DataSource, user_id: &str, data_source_id: &str) -> UserDataSourceUpdateCall<'a, C, NC, A> { + UserDataSourceUpdateCall { + hub: self.hub, + _request: request.clone(), + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists sessions previously created. + pub fn sessions_list(&self, user_id: &str) -> UserSessionListCall<'a, C, NC, A> { + UserSessionListCall { + hub: self.hub, + _user_id: user_id.to_string(), + _start_time: Default::default(), + _page_token: Default::default(), + _include_deleted: Default::default(), + _end_time: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates or insert a given session. + pub fn sessions_update(&self, request: &Session, user_id: &str, session_id: &str) -> UserSessionUpdateCall<'a, C, NC, A> { + UserSessionUpdateCall { + hub: self.hub, + _request: request.clone(), + _user_id: user_id.to_string(), + _session_id: session_id.to_string(), + _current_time_millis: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a given data source. It is an error to modify the data source's data stream ID, data type, type, stream name or device information apart from the device version. Changing these fields would require a new unique data stream ID and separate data source. + /// + /// Data sources are identified by their data stream ID. This method supports patch semantics. + pub fn data_sources_patch(&self, request: &DataSource, user_id: &str, data_source_id: &str) -> UserDataSourcePatchCall<'a, C, NC, A> { + UserDataSourcePatchCall { + hub: self.hub, + _request: request.clone(), + _user_id: user_id.to_string(), + _data_source_id: data_source_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists all data sources that are visible to the developer, using the OAuth scopes provided. The list is not exhaustive: the user may have private data sources that are only visible to other developers or calls using other scopes. + pub fn data_sources_list(&self, user_id: &str) -> UserDataSourceListCall<'a, C, NC, A> { + UserDataSourceListCall { + hub: self.hub, + _user_id: user_id.to_string(), + _data_type_name: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns a dataset containing all data points whose start and end times overlap with the specified range of the dataset minimum start time and maximum end time. Specifically, any data point whose start time is less than or equal to the dataset end time and whose end time is greater than or equal to the dataset start time. +/// +/// A builder for the *dataSources.datasets.get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_datasets_get("userId", "dataSourceId", "datasetId") +/// .page_token("justo") +/// .limit(-1) +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceDatasetGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _data_source_id: String, + _dataset_id: String, + _page_token: Option, + _limit: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceDatasetGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceDatasetGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.datasets.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._limit { + params.push(("limit", value.to_string())); + } + for &field in ["alt", "userId", "dataSourceId", "datasetId", "pageToken", "limit"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["userId", "dataSourceId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Retrieve a dataset for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source that created the dataset. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset identifier that is a composite of the minimum data point start time and maximum data point end time represented as nanoseconds from the epoch. The ID is formatted like: "startTime-endTime" where startTime and endTime are 64 bit integers. + pub fn dataset_id(mut self, new_value: &str) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The continuation token, which is used to page through large datasets. To get the next page of a dataset, set this parameter to the value of nextPageToken from the previous response. Each subsequent call will yield a partial dataset with data point end timestamps that are strictly smaller than those in the previous partial response. + pub fn page_token(mut self, new_value: &str) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *limit* query property to the given value. + /// + /// + /// If specified, no more than this many data points will be included in the dataset. If the there are more data points in the dataset, nextPageToken will be set in the dataset response. + pub fn limit(mut self, new_value: i32) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._limit = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceDatasetGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceDatasetGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceDatasetGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Creates a new data source that is unique across all data sources belonging to this user. The data stream ID field can be omitted and will be generated by the server with the correct format. The data stream ID is an ordered combination of some fields from the data source. In addition to the data source fields reflected into the data source ID, the developer project number that is authenticated when creating the data source is included. This developer project number is obfuscated when read by any other developer reading public data types. +/// +/// A builder for the *dataSources.create* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// use fitness1::DataSource; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DataSource = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_create(&req, "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceCreateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _request: DataSource, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceCreateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceCreateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DataSource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DataSource) -> UserDataSourceCreateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Create the data source for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceCreateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceCreateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceCreateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceCreateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Performs an inclusive delete of all data points whose start and end times have any overlap with the time range specified by the dataset ID. For most data types, the entire data point will be deleted. For data types where the time span represents a consistent value (such as com.google.activity.segment), and a data point straddles either end point of the dataset, only the overlapping portion of the data point will be deleted. +/// +/// A builder for the *dataSources.datasets.delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_datasets_delete("userId", "dataSourceId", "datasetId") +/// .modified_time_millis("dolores") +/// .current_time_millis("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceDatasetDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _data_source_id: String, + _dataset_id: String, + _modified_time_millis: Option, + _current_time_millis: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceDatasetDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceDatasetDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.datasets.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._modified_time_millis { + params.push(("modifiedTimeMillis", value.to_string())); + } + if let Some(value) = self._current_time_millis { + params.push(("currentTimeMillis", value.to_string())); + } + for &field in ["userId", "dataSourceId", "datasetId", "modifiedTimeMillis", "currentTimeMillis"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["userId", "dataSourceId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Delete a dataset for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source that created the dataset. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset identifier that is a composite of the minimum data point start time and maximum data point end time represented as nanoseconds from the epoch. The ID is formatted like: "startTime-endTime" where startTime and endTime are 64 bit integers. + pub fn dataset_id(mut self, new_value: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *modified time millis* query property to the given value. + /// + /// + /// When the operation was performed on the client. + pub fn modified_time_millis(mut self, new_value: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._modified_time_millis = Some(new_value.to_string()); + self + } + /// Sets the *current time millis* query property to the given value. + /// + /// + /// The client's current time in milliseconds since epoch. + pub fn current_time_millis(mut self, new_value: &str) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._current_time_millis = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceDatasetDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Adds data points to a dataset. The dataset need not be previously created. All points within the given dataset will be returned with subsquent calls to retrieve this dataset. Data points can belong to more than one dataset. This method does not use patch semantics. +/// +/// A builder for the *dataSources.datasets.patch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// use fitness1::Dataset; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Dataset = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_datasets_patch(&req, "userId", "dataSourceId", "datasetId") +/// .current_time_millis("no") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceDatasetPatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _request: Dataset, + _user_id: String, + _data_source_id: String, + _dataset_id: String, + _current_time_millis: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceDatasetPatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceDatasetPatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Dataset)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.datasets.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._current_time_millis { + params.push(("currentTimeMillis", value.to_string())); + } + for &field in ["alt", "userId", "dataSourceId", "datasetId", "currentTimeMillis"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId"), ("{datasetId}", "datasetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["userId", "dataSourceId", "datasetId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Dataset) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Patch a dataset for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source that created the dataset. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *dataset id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Dataset identifier that is a composite of the minimum data point start time and maximum data point end time represented as nanoseconds from the epoch. The ID is formatted like: "startTime-endTime" where startTime and endTime are 64 bit integers. + pub fn dataset_id(mut self, new_value: &str) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._dataset_id = new_value.to_string(); + self + } + /// Sets the *current time millis* query property to the given value. + /// + /// + /// The client's current time in milliseconds since epoch. Note that the minStartTimeNs and maxEndTimeNs properties in the request body are in nanoseconds instead of milliseconds. + pub fn current_time_millis(mut self, new_value: &str) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._current_time_millis = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceDatasetPatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Deletes a session specified by the given session ID. +/// +/// A builder for the *sessions.delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().sessions_delete("userId", "sessionId") +/// .current_time_millis("et") +/// .doit(); +/// # } +/// ``` +pub struct UserSessionDeleteCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _session_id: String, + _current_time_millis: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserSessionDeleteCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserSessionDeleteCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.sessions.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("sessionId", self._session_id.to_string())); + if let Some(value) = self._current_time_millis { + params.push(("currentTimeMillis", value.to_string())); + } + for &field in ["userId", "sessionId", "currentTimeMillis"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/sessions/{sessionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{sessionId}", "sessionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "sessionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Delete, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Delete a session for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserSessionDeleteCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *session id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the session to be deleted. + pub fn session_id(mut self, new_value: &str) -> UserSessionDeleteCall<'a, C, NC, A> { + self._session_id = new_value.to_string(); + self + } + /// Sets the *current time millis* query property to the given value. + /// + /// + /// The client's current time in milliseconds since epoch. + pub fn current_time_millis(mut self, new_value: &str) -> UserSessionDeleteCall<'a, C, NC, A> { + self._current_time_millis = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserSessionDeleteCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserSessionDeleteCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserSessionDeleteCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Returns a data source identified by a data stream ID. +/// +/// A builder for the *dataSources.get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_get("userId", "dataSourceId") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceGetCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _data_source_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceGetCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceGetCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DataSource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + for &field in ["alt", "userId", "dataSourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "dataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Retrieve a data source for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceGetCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source to retrieve. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourceGetCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceGetCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceGetCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceGetCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a given data source. It is an error to modify the data source's data stream ID, data type, type, stream name or device information apart from the device version. Changing these fields would require a new unique data stream ID and separate data source. +/// +/// Data sources are identified by their data stream ID. +/// +/// A builder for the *dataSources.update* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// use fitness1::DataSource; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DataSource = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_update(&req, "userId", "dataSourceId") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _request: DataSource, + _user_id: String, + _data_source_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DataSource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + for &field in ["alt", "userId", "dataSourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "dataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DataSource) -> UserDataSourceUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Update the data source for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceUpdateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source to update. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourceUpdateCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists sessions previously created. +/// +/// A builder for the *sessions.list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().sessions_list("userId") +/// .start_time("duo") +/// .page_token("aliquyam") +/// .include_deleted(true) +/// .end_time("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct UserSessionListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _start_time: Option, + _page_token: Option, + _include_deleted: Option, + _end_time: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserSessionListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserSessionListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListSessionsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.sessions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + if let Some(value) = self._start_time { + params.push(("startTime", value.to_string())); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._include_deleted { + params.push(("includeDeleted", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + for &field in ["alt", "userId", "startTime", "pageToken", "includeDeleted", "endTime"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/sessions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// List sessions for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserSessionListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *start time* query property to the given value. + /// + /// + /// An RFC3339 timestamp. Only sessions ending between the start and end times will be included in the response. + pub fn start_time(mut self, new_value: &str) -> UserSessionListCall<'a, C, NC, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// Sets the *page token* query property to the given value. + /// + /// + /// The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of nextPageToken from the previous response. + pub fn page_token(mut self, new_value: &str) -> UserSessionListCall<'a, C, NC, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sets the *include deleted* query property to the given value. + /// + /// + /// If true, deleted sessions will be returned. When set to true, sessions returned in this response will only have an ID and will not have any other fields. + pub fn include_deleted(mut self, new_value: bool) -> UserSessionListCall<'a, C, NC, A> { + self._include_deleted = Some(new_value); + self + } + /// Sets the *end time* query property to the given value. + /// + /// + /// An RFC3339 timestamp. Only sessions ending between the start and end times will be included in the response. + pub fn end_time(mut self, new_value: &str) -> UserSessionListCall<'a, C, NC, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserSessionListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserSessionListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserSessionListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates or insert a given session. +/// +/// A builder for the *sessions.update* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// use fitness1::Session; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: Session = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().sessions_update(&req, "userId", "sessionId") +/// .current_time_millis("sadipscing") +/// .doit(); +/// # } +/// ``` +pub struct UserSessionUpdateCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _request: Session, + _user_id: String, + _session_id: String, + _current_time_millis: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserSessionUpdateCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserSessionUpdateCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Session)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.sessions.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("sessionId", self._session_id.to_string())); + if let Some(value) = self._current_time_millis { + params.push(("currentTimeMillis", value.to_string())); + } + for &field in ["alt", "userId", "sessionId", "currentTimeMillis"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/sessions/{sessionId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{sessionId}", "sessionId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "sessionId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &Session) -> UserSessionUpdateCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Create sessions for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserSessionUpdateCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *session id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The ID of the session to be created. + pub fn session_id(mut self, new_value: &str) -> UserSessionUpdateCall<'a, C, NC, A> { + self._session_id = new_value.to_string(); + self + } + /// Sets the *current time millis* query property to the given value. + /// + /// + /// The client's current time in milliseconds since epoch. + pub fn current_time_millis(mut self, new_value: &str) -> UserSessionUpdateCall<'a, C, NC, A> { + self._current_time_millis = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserSessionUpdateCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserSessionUpdateCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserSessionUpdateCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Updates a given data source. It is an error to modify the data source's data stream ID, data type, type, stream name or device information apart from the device version. Changing these fields would require a new unique data stream ID and separate data source. +/// +/// Data sources are identified by their data stream ID. This method supports patch semantics. +/// +/// A builder for the *dataSources.patch* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// use fitness1::DataSource; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req: DataSource = Default::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_patch(&req, "userId", "dataSourceId") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourcePatchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _request: DataSource, + _user_id: String, + _data_source_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourcePatchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourcePatchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DataSource)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + params.push(("dataSourceId", self._data_source_id.to_string())); + for &field in ["alt", "userId", "dataSourceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId"), ("{dataSourceId}", "dataSourceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["userId", "dataSourceId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = io::Cursor::new(json::to_vec(&self._request)); + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Patch, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + pub fn request(mut self, new_value: &DataSource) -> UserDataSourcePatchCall<'a, C, NC, A> { + self._request = new_value.clone(); + self + } + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// Update the data source for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourcePatchCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Sets the *data source id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// The data stream ID of the data source to update. + pub fn data_source_id(mut self, new_value: &str) -> UserDataSourcePatchCall<'a, C, NC, A> { + self._data_source_id = new_value.to_string(); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourcePatchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourcePatchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourcePatchCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + +/// Lists all data sources that are visible to the developer, using the OAuth scopes provided. The list is not exhaustive: the user may have private data sources that are only visible to other developers or calls using other scopes. +/// +/// A builder for the *dataSources.list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-fitness1" as fitness1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use fitness1::Fitness; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Fitness::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.users().data_sources_list("userId") +/// .add_data_type_name("amet") +/// .doit(); +/// # } +/// ``` +pub struct UserDataSourceListCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Fitness, + _user_id: String, + _data_type_name: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, NC, A> CallBuilder for UserDataSourceListCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> UserDataSourceListCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListDataSourcesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "fitness.users.dataSources.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("userId", self._user_id.to_string())); + if self._data_type_name.len() > 0 { + let mut s = String::new(); + for f in self._data_type_name.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("dataTypeName", s)); + } + for &field in ["alt", "userId", "dataTypeName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/fitness/v1/users/{userId}/dataSources".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ActivityRead.as_slice().to_string(), ()); + } + + for &(find_this, param_name) in [("{userId}", "userId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["userId"].iter() { + for (index, &(ref name, _)) in params.iter().rev().enumerate() { + if name == param_name { + indices_for_removal.push(params.len() - index - 1); + break; + } + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut token = self.hub.auth.borrow_mut().token(self._scopes.keys()); + if token.is_none() { + token = dlg.token(); + } + if token.is_none() { + dlg.finished(false); + return Result::MissingToken + } + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.unwrap().access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Sets the *user id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + /// + /// List data sources for the person identified. Use me to indicate the authenticated user. Only me is supported at this time. + pub fn user_id(mut self, new_value: &str) -> UserDataSourceListCall<'a, C, NC, A> { + self._user_id = new_value.to_string(); + self + } + /// Append the given value to the *data type name* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The names of data types to include in the list. If not specified, all data sources will be returned. + pub fn add_data_type_name(mut self, new_value: &str) -> UserDataSourceListCall<'a, C, NC, A> { + self._data_type_name.push(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDataSourceListCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserDataSourceListCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead of relying on the + /// automated algorithm which simply prefers read-only scopes over those who are not. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserDataSourceListCall<'a, C, NC, A> + where T: Str { + self._scopes.insert(scope.as_slice().to_string(), ()); + self + } +} + + diff --git a/gen/freebase1/Cargo.toml b/gen/freebase1/Cargo.toml new file mode 100644 index 0000000000..f74f135493 --- /dev/null +++ b/gen/freebase1/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-freebase1" +version = "0.1.0+20150313" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with freebase (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/freebase1" +homepage = "https://developers.google.com/freebase/" +documentation = "http://byron.github.io/google-apis-rs/google-freebase1" +license = "MIT" +keywords = ["freebase", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/freebase1/LICENSE.md b/gen/freebase1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/freebase1/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/freebase1/README.md b/gen/freebase1/README.md new file mode 100644 index 0000000000..c0144bdceb --- /dev/null +++ b/gen/freebase1/README.md @@ -0,0 +1,173 @@ + +The `google-freebase1` library allows access to all features of the *Google freebase* service. + +This documentation was generated from *freebase* crate version *0.1.0+20150313*, where *20150313* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *freebase* *v1* API can be found at the +[official documentation site](https://developers.google.com/freebase/). +# Features + +Use the following functionality with ease from the central [hub](http://byron.github.io/google-apis-rs/google-freebase1/struct.Freebase.html) ... + + +* [reconcile](http://byron.github.io/google-apis-rs/google-freebase1/struct.MethodReconcileCall.html) +* [search](http://byron.github.io/google-apis-rs/google-freebase1/struct.MethodSearchCall.html) + +Download supported by ... + +* [*search*](http://byron.github.io/google-apis-rs/google-freebase1/struct.MethodSearchCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-freebase1/struct.Freebase.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-freebase1/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-freebase1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-freebase1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.methods().reconcile(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-freebase1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-freebase1" as freebase1; +use freebase1::Result; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use freebase1::Freebase; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Freebase::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.methods().reconcile() + .add_prop("eirmod") + .name("sit") + .limit(-65) + .add_lang("sed") + .add_kind("et") + .confidence(0.824373746908) + .doit(); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-freebase1/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-freebase1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-freebase1/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-freebase1/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-freebase1/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-freebase1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-freebase1/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-freebase1/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-freebase1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-freebase1/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-freebase1/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-freebase1/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-freebase1/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **freebase1** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/freebase1/src/cmn.rs b/gen/freebase1/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/freebase1/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/freebase1/src/lib.rs b/gen/freebase1/src/lib.rs new file mode 100644 index 0000000000..ea30ea8c7d --- /dev/null +++ b/gen/freebase1/src/lib.rs @@ -0,0 +1,1280 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *freebase* crate version *0.1.0+20150313*, where *20150313* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *freebase* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/freebase/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/freebase1). +//! # Features +//! +//! Use the following functionality with ease from the central [hub](struct.Freebase.html) ... +//! +//! +//! * [reconcile](struct.MethodReconcileCall.html) +//! * [search](struct.MethodSearchCall.html) +//! +//! Download supported by ... +//! +//! * [*search*](struct.MethodSearchCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Freebase.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.methods().reconcile(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-freebase1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-freebase1" as freebase1; +//! use freebase1::Result; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use freebase1::Freebase; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Freebase::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.methods().reconcile() +//! .add_prop("kasd") +//! .name("accusam") +//! .limit(-8) +//! .add_lang("justo") +//! .add_kind("amet.") +//! .confidence(0.204946002078) +//! .doit(); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Freebase related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-freebase1" as freebase1; +/// use freebase1::Result; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use freebase1::Freebase; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Freebase::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.methods().reconcile() +/// .add_prop("labore") +/// .name("sea") +/// .limit(-90) +/// .add_lang("dolores") +/// .add_kind("gubergren") +/// .confidence(0.0653431304201) +/// .doit(); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Freebase { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Freebase {} + +impl<'a, C, NC, A> Freebase + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Freebase { + Freebase { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn methods(&'a self) -> MethodMethods<'a, C, NC, A> { + MethodMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// There is no detailed description. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReconcileCandidate { + /// Language code that candidate and notable names are displayed in. + pub lang: String, + /// Percentage likelihood that this candidate is the unique matching entity. Value will be between 0.0 and 1.0 + pub confidence: f32, + /// Type or profession the candidate is notable for. + pub notable: ReconcileCandidateNotable, + /// Freebase MID of candidate entity. + pub mid: String, + /// Freebase name of matching entity in specified language. + pub name: String, +} + +impl Part for ReconcileCandidate {} + + +/// If filled, then there were recoverable problems that affected the request. For example, some of the properties were ignored because they either are not valid Freebase predicates or are not indexed for reconciliation. The candidates returned should be considered valid results, with the caveat that sections of the request were ignored as specified by the warning text. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReconcileGetWarning { + /// Code for identifying classes of warnings. + pub reason: String, + /// Warning message to display to the user. + pub message: String, + /// Location of warning in the request e.g. invalid predicate. + pub location: String, +} + +impl NestedType for ReconcileGetWarning {} +impl Part for ReconcileGetWarning {} + + +/// Server costs for reconciling. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReconcileGetCosts { + /// Total number of hits found. + pub hits: i32, + /// Total milliseconds spent. + pub ms: i32, +} + +impl NestedType for ReconcileGetCosts {} +impl Part for ReconcileGetCosts {} + + +/// There is no detailed description. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [reconcile](struct.MethodReconcileCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReconcileGet { + /// Server costs for reconciling. + pub costs: ReconcileGetCosts, + /// If filled, then there were recoverable problems that affected the request. For example, some of the properties were ignored because they either are not valid Freebase predicates or are not indexed for reconciliation. The candidates returned should be considered valid results, with the caveat that sections of the request were ignored as specified by the warning text. + pub warning: Vec, + /// If filled, then the listed candidates are potential matches, and such should be evaluated by a more discerning algorithm or human. The matches are ordered by confidence. + pub candidate: Vec, + /// If filled, this entity is guaranteed to match at requested confidence probability (default 99%). + #[serde(alias="match")] + pub match_: ReconcileCandidate, +} + +impl ResponseResult for ReconcileGet {} + + +/// Type or profession the candidate is notable for. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ReconcileCandidateNotable { + /// MID of notable category. + pub id: String, + /// Name of notable category in specified language. + pub name: String, +} + +impl NestedType for ReconcileCandidateNotable {} +impl Part for ReconcileCandidateNotable {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all free methods, which are not associated with a particular resource. +/// It is not used directly, but through the `Freebase` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-freebase1" as freebase1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use freebase1::Freebase; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Freebase::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `reconcile(...)` and `search(...)` +/// // to build up your call. +/// let rb = hub.methods(); +/// # } +/// ``` +pub struct MethodMethods<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Freebase, +} + +impl<'a, C, NC, A> ResourceMethodsBuilder for MethodMethods<'a, C, NC, A> {} + +impl<'a, C, NC, A> MethodMethods<'a, C, NC, A> { + + /// Create a builder to help you perform the following task: + /// + /// Reconcile entities to Freebase open data. + pub fn reconcile(&self) -> MethodReconcileCall<'a, C, NC, A> { + MethodReconcileCall { + hub: self.hub, + _prop: Default::default(), + _name: Default::default(), + _limit: Default::default(), + _lang: Default::default(), + _kind: Default::default(), + _confidence: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Search Freebase open data. + pub fn search(&self) -> MethodSearchCall<'a, C, NC, A> { + MethodSearchCall { + hub: self.hub, + _without: Default::default(), + _with: Default::default(), + _type_: Default::default(), + _stemmed: Default::default(), + _spell: Default::default(), + _scoring: Default::default(), + _query: Default::default(), + _prefixed: Default::default(), + _output: Default::default(), + _mql_output: Default::default(), + _mid: Default::default(), + _limit: Default::default(), + _lang: Default::default(), + _indent: Default::default(), + _help: Default::default(), + _format: Default::default(), + _filter: Default::default(), + _exact: Default::default(), + _encode: Default::default(), + _domain: Default::default(), + _cursor: Default::default(), + _callback: Default::default(), + _as_of_time: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Reconcile entities to Freebase open data. +/// +/// A builder for the *reconcile* method. +/// It is not used directly, but through a `MethodMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-freebase1" as freebase1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use freebase1::Freebase; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Freebase::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.methods().reconcile() +/// .add_prop("aliquyam") +/// .name("ea") +/// .limit(-61) +/// .add_lang("justo") +/// .add_kind("justo") +/// .confidence(0.663748882844) +/// .doit(); +/// # } +/// ``` +pub struct MethodReconcileCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Freebase, + _prop: Vec, + _name: Option, + _limit: Option, + _lang: Vec, + _kind: Vec, + _confidence: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for MethodReconcileCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MethodReconcileCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ReconcileGet)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "freebase.reconcile", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + if self._prop.len() > 0 { + let mut s = String::new(); + for f in self._prop.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("prop", s)); + } + if let Some(value) = self._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._limit { + params.push(("limit", value.to_string())); + } + if self._lang.len() > 0 { + let mut s = String::new(); + for f in self._lang.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("lang", s)); + } + if self._kind.len() > 0 { + let mut s = String::new(); + for f in self._kind.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("kind", s)); + } + if let Some(value) = self._confidence { + params.push(("confidence", value.to_string())); + } + for &field in ["alt", "prop", "name", "limit", "lang", "kind", "confidence"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/freebase/v1/reconcile".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Result::JsonDecodeError(err); + } + } + }; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *prop* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Property values for entity formatted as + /// : + pub fn add_prop(mut self, new_value: &str) -> MethodReconcileCall<'a, C, NC, A> { + self._prop.push(new_value.to_string()); + self + } + /// Sets the *name* query property to the given value. + /// + /// + /// Name of entity. + pub fn name(mut self, new_value: &str) -> MethodReconcileCall<'a, C, NC, A> { + self._name = Some(new_value.to_string()); + self + } + /// Sets the *limit* query property to the given value. + /// + /// + /// Maximum number of candidates to return. + pub fn limit(mut self, new_value: i32) -> MethodReconcileCall<'a, C, NC, A> { + self._limit = Some(new_value); + self + } + /// Append the given value to the *lang* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Languages for names and values. First language is used for display. Default is 'en'. + pub fn add_lang(mut self, new_value: &str) -> MethodReconcileCall<'a, C, NC, A> { + self._lang.push(new_value.to_string()); + self + } + /// Append the given value to the *kind* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Classifications of entity e.g. type, category, title. + pub fn add_kind(mut self, new_value: &str) -> MethodReconcileCall<'a, C, NC, A> { + self._kind.push(new_value.to_string()); + self + } + /// Sets the *confidence* query property to the given value. + /// + /// + /// Required confidence for a candidate to match. Must be between .5 and 1.0 + pub fn confidence(mut self, new_value: f32) -> MethodReconcileCall<'a, C, NC, A> { + self._confidence = Some(new_value); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MethodReconcileCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MethodReconcileCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + +/// Search Freebase open data. +/// +/// This method supports **media download**. To enable it, adjust the builder like this: +/// `.param("alt", "media")`. +/// +/// A builder for the *search* method. +/// It is not used directly, but through a `MethodMethods`. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate "yup-oauth2" as oauth2; +/// # extern crate "google-freebase1" as freebase1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use freebase1::Freebase; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Freebase::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.methods().search() +/// .add_without("et") +/// .add_with("diam") +/// .add_type("ipsum") +/// .stemmed(true) +/// .spell("et") +/// .scoring("duo") +/// .query("aliquyam") +/// .prefixed(true) +/// .output("Lorem") +/// .mql_output("eos") +/// .add_mid("erat") +/// .limit(-95) +/// .add_lang("dolor") +/// .indent(true) +/// .help("elitr") +/// .format("amet") +/// .add_filter("no") +/// .exact(true) +/// .encode("eirmod") +/// .add_domain("dolore") +/// .cursor(-37) +/// .callback("aliquyam") +/// .as_of_time("accusam") +/// .doit(); +/// # } +/// ``` +pub struct MethodSearchCall<'a, C, NC, A> + where C: 'a, NC: 'a, A: 'a { + + hub: &'a Freebase, + _without: Vec, + _with: Vec, + _type_: Vec, + _stemmed: Option, + _spell: Option, + _scoring: Option, + _query: Option, + _prefixed: Option, + _output: Option, + _mql_output: Option, + _mid: Vec, + _limit: Option, + _lang: Vec, + _indent: Option, + _help: Option, + _format: Option, + _filter: Vec, + _exact: Option, + _encode: Option, + _domain: Vec, + _cursor: Option, + _callback: Option, + _as_of_time: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, NC, A> CallBuilder for MethodSearchCall<'a, C, NC, A> {} + +impl<'a, C, NC, A> MethodSearchCall<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "freebase.search", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((24 + self._additional_params.len())); + if self._without.len() > 0 { + let mut s = String::new(); + for f in self._without.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("without", s)); + } + if self._with.len() > 0 { + let mut s = String::new(); + for f in self._with.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("with", s)); + } + if self._type_.len() > 0 { + let mut s = String::new(); + for f in self._type_.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("type", s)); + } + if let Some(value) = self._stemmed { + params.push(("stemmed", value.to_string())); + } + if let Some(value) = self._spell { + params.push(("spell", value.to_string())); + } + if let Some(value) = self._scoring { + params.push(("scoring", value.to_string())); + } + if let Some(value) = self._query { + params.push(("query", value.to_string())); + } + if let Some(value) = self._prefixed { + params.push(("prefixed", value.to_string())); + } + if let Some(value) = self._output { + params.push(("output", value.to_string())); + } + if let Some(value) = self._mql_output { + params.push(("mql_output", value.to_string())); + } + if self._mid.len() > 0 { + let mut s = String::new(); + for f in self._mid.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("mid", s)); + } + if let Some(value) = self._limit { + params.push(("limit", value.to_string())); + } + if self._lang.len() > 0 { + let mut s = String::new(); + for f in self._lang.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("lang", s)); + } + if let Some(value) = self._indent { + params.push(("indent", value.to_string())); + } + if let Some(value) = self._help { + params.push(("help", value.to_string())); + } + if let Some(value) = self._format { + params.push(("format", value.to_string())); + } + if self._filter.len() > 0 { + let mut s = String::new(); + for f in self._filter.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("filter", s)); + } + if let Some(value) = self._exact { + params.push(("exact", value.to_string())); + } + if let Some(value) = self._encode { + params.push(("encode", value.to_string())); + } + if self._domain.len() > 0 { + let mut s = String::new(); + for f in self._domain.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("domain", s)); + } + if let Some(value) = self._cursor { + params.push(("cursor", value.to_string())); + } + if let Some(value) = self._callback { + params.push(("callback", value.to_string())); + } + if let Some(value) = self._as_of_time { + params.push(("as_of_time", value.to_string())); + } + for &field in ["without", "with", "type", "stemmed", "spell", "scoring", "query", "prefixed", "output", "mql_output", "mid", "limit", "lang", "indent", "help", "format", "filter", "exact", "encode", "domain", "cursor", "callback", "as_of_time"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Result::FieldClash(field); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/freebase/v1/search".to_string(); + + let mut key = self.hub.auth.borrow_mut().api_key(); + if key.is_none() { + key = dlg.api_key(); + } + match key { + Some(value) => params.push(("key", value)), + None => { + dlg.finished(false); + return Result::MissingAPIKey + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params.iter().map(|t| (t.0, t.1.as_slice())))); + } + + + + loop { + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.as_slice()) + .header(UserAgent(self.hub._user_agent.clone())); + + dlg.pre_request(); + req.send() + + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::HttpError(err) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + dlg.finished(false); + return Result::Failure(res) + } + let result_value = res; + + dlg.finished(true); + return Result::Success(result_value) + } + } + } + } + + + /// Append the given value to the *without* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A rule to not match against. + pub fn add_without(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._without.push(new_value.to_string()); + self + } + /// Append the given value to the *with* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A rule to match against. + pub fn add_with(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._with.push(new_value.to_string()); + self + } + /// Append the given value to the *type* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Restrict to topics with this Freebase type id. + pub fn add_type(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._type_.push(new_value.to_string()); + self + } + /// Sets the *stemmed* query property to the given value. + /// + /// + /// Query on stemmed names and aliases. May not be used with prefixed. + pub fn stemmed(mut self, new_value: bool) -> MethodSearchCall<'a, C, NC, A> { + self._stemmed = Some(new_value); + self + } + /// Sets the *spell* query property to the given value. + /// + /// + /// Request 'did you mean' suggestions + pub fn spell(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._spell = Some(new_value.to_string()); + self + } + /// Sets the *scoring* query property to the given value. + /// + /// + /// Relevance scoring algorithm to use. + pub fn scoring(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._scoring = Some(new_value.to_string()); + self + } + /// Sets the *query* query property to the given value. + /// + /// + /// Query term to search for. + pub fn query(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._query = Some(new_value.to_string()); + self + } + /// Sets the *prefixed* query property to the given value. + /// + /// + /// Prefix match against names and aliases. + pub fn prefixed(mut self, new_value: bool) -> MethodSearchCall<'a, C, NC, A> { + self._prefixed = Some(new_value); + self + } + /// Sets the *output* query property to the given value. + /// + /// + /// An output expression to request data from matches. + pub fn output(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._output = Some(new_value.to_string()); + self + } + /// Sets the *mql_output* query property to the given value. + /// + /// + /// The MQL query to run againist the results to extract more data. + pub fn mql_output(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._mql_output = Some(new_value.to_string()); + self + } + /// Append the given value to the *mid* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A mid to use instead of a query. + pub fn add_mid(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._mid.push(new_value.to_string()); + self + } + /// Sets the *limit* query property to the given value. + /// + /// + /// Maximum number of results to return. + pub fn limit(mut self, new_value: i32) -> MethodSearchCall<'a, C, NC, A> { + self._limit = Some(new_value); + self + } + /// Append the given value to the *lang* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// The code of the language to run the query with. Default is 'en'. + pub fn add_lang(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._lang.push(new_value.to_string()); + self + } + /// Sets the *indent* query property to the given value. + /// + /// + /// Whether to indent the json results or not. + pub fn indent(mut self, new_value: bool) -> MethodSearchCall<'a, C, NC, A> { + self._indent = Some(new_value); + self + } + /// Sets the *help* query property to the given value. + /// + /// + /// The keyword to request help on. + pub fn help(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._help = Some(new_value.to_string()); + self + } + /// Sets the *format* query property to the given value. + /// + /// + /// Structural format of the json response. + pub fn format(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._format = Some(new_value.to_string()); + self + } + /// Append the given value to the *filter* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// A filter to apply to the query. + pub fn add_filter(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._filter.push(new_value.to_string()); + self + } + /// Sets the *exact* query property to the given value. + /// + /// + /// Query on exact name and keys only. + pub fn exact(mut self, new_value: bool) -> MethodSearchCall<'a, C, NC, A> { + self._exact = Some(new_value); + self + } + /// Sets the *encode* query property to the given value. + /// + /// + /// The encoding of the response. You can use this parameter to enable html encoding. + pub fn encode(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._encode = Some(new_value.to_string()); + self + } + /// Append the given value to the *domain* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + /// + /// + /// Restrict to topics with this Freebase domain id. + pub fn add_domain(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._domain.push(new_value.to_string()); + self + } + /// Sets the *cursor* query property to the given value. + /// + /// + /// The cursor value to use for the next page of results. + pub fn cursor(mut self, new_value: i32) -> MethodSearchCall<'a, C, NC, A> { + self._cursor = Some(new_value); + self + } + /// Sets the *callback* query property to the given value. + /// + /// + /// JS method name for JSONP callbacks. + pub fn callback(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._callback = Some(new_value.to_string()); + self + } + /// Sets the *as_of_time* query property to the given value. + /// + /// + /// A mql as_of_time value to use with mql_output queries. + pub fn as_of_time(mut self, new_value: &str) -> MethodSearchCall<'a, C, NC, A> { + self._as_of_time = Some(new_value.to_string()); + self + } + /// Sets the *delegate* property to the given value. + /// + /// + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MethodSearchCall<'a, C, NC, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MethodSearchCall<'a, C, NC, A> + where T: Str { + self._additional_params.insert(name.as_slice().to_string(), value.as_slice().to_string()); + self + } + +} + + diff --git a/gen/fusiontables2/Cargo.toml b/gen/fusiontables2/Cargo.toml new file mode 100644 index 0000000000..2046e9d174 --- /dev/null +++ b/gen/fusiontables2/Cargo.toml @@ -0,0 +1,22 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-fusiontables2" +version = "0.1.0+20141113" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with fusiontables (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/fusiontables2" +homepage = "https://developers.google.com/fusiontables" +documentation = "http://byron.github.io/google-apis-rs/google-fusiontables2" +license = "MIT" +keywords = ["fusiontables", "google", "protocol", "web", "api"] + +[dependencies] +hyper = "*" +mime = "*" +url = "*" +serde = "*" +serde_macros = "*" +yup-oauth2 = "*" diff --git a/gen/fusiontables2/LICENSE.md b/gen/fusiontables2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/fusiontables2/LICENSE.md @@ -0,0 +1,30 @@ + +The MIT License (MIT) +===================== + +Copyright © `2015` `Sebastian Thiel` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/gen/fusiontables2/README.md b/gen/fusiontables2/README.md new file mode 100644 index 0000000000..9554005b95 --- /dev/null +++ b/gen/fusiontables2/README.md @@ -0,0 +1,192 @@ + +The `google-fusiontables2` library allows access to all features of the *Google fusiontables* service. + +This documentation was generated from *fusiontables* crate version *0.1.0+20141113*, where *20141113* is the exact revision of the *fusiontables:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. + +Everything else about the *fusiontables* *v2* API can be found at the +[official documentation site](https://developers.google.com/fusiontables). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Fusiontables.html) ... + +* [column](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Column.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.ColumnUpdateCall.html) +* query + * [*sql*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.QuerySqlCall.html) and [*sql get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.QuerySqlGetCall.html) +* style + * [*delete*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StyleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StyleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StyleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StyleListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StylePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.StyleUpdateCall.html) +* [table](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Table.html) + * [*copy*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableCopyCall.html), [*delete*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableGetCall.html), [*import rows*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableImportRowCall.html), [*import table*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableImportTableCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TablePatchCall.html), [*replace rows*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableReplaceRowCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableUpdateCall.html) +* [task](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Task.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TaskDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TaskGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TaskListCall.html) +* [template](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Template.html) + * [*delete*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplateDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplateGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplateInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplateListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplatePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TemplateUpdateCall.html) + + +Upload supported by ... + +* [*replace rows table*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableReplaceRowCall.html) +* [*import rows table*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableImportRowCall.html) +* [*import table table*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.TableImportTableCall.html) + +Download supported by ... + +* [*sql get query*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.QuerySqlGetCall.html) +* [*sql query*](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.QuerySqlCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google-fusiontables2/struct.Fusiontables.html)** + * a central object to maintain state and allow accessing all *Activities* +* **[Resources](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Resource.html)** + * primary types that you can apply *Activities* to + * a collection of properties and *Parts* + * **[Parts](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.table().import_table(...).doit() +let r = hub.table().patch(...).doit() +let r = hub.table().get(...).doit() +let r = hub.table().copy(...).doit() +let r = hub.table().insert(...).doit() +let r = hub.table().update(...).doit() +``` + +The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +The `doit()` method performs the actual communication with the server and returns the respective result. + +# Usage + +## Setting up your Project + +To use this library, you would put the following lines into your `Cargo.toml` file: + +```toml +[dependencies] +google-fusiontables2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate "yup-oauth2" as oauth2; +extern crate "google-fusiontables2" as fusiontables2; +use fusiontables2::Result; +use std::fs; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use fusiontables2::Fusiontables; + +// Get an ApplicationSecret instance by some means. It contains the `client_id` and +// `client_secret`, among other things. +let secret: ApplicationSecret = Default::default(); +// Instantiate the authenticator. It will choose a suitable authentication flow for you, +// unless you replace `None` with the desired Flow. +// Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +// what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +// retrieve them from storage. +let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, + hyper::Client::new(), + ::default(), None); +let mut hub = Fusiontables::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `upload_resumable(...)`. +// Values shown here are possibly random and not representative ! +let result = hub.table().import_table("name") + .encoding("sit") + .delimiter("Stet") + .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); + +match result { + Result::HttpError(err) => println!("HTTPERROR: {:?}", err), + Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), + Result::MissingToken => println!("OAuth2: Missing Token"), + Result::Cancelled => println!("Operation cancelled by user"), + Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), + Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), + Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), + Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), + Result::Success(_) => println!("Success (value doesn't print)"), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google-fusiontables2/enum.Result.html) enumeration as return value of +the doit() methods, or handed as possibly intermediate results to either the +[Hub Delegate](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google-fusiontables2/../yup-oauth2/trait.AuthenticatorDelegate.html). + +When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +makes the system potentially resilient to all kinds of errors. + +## Uploads and Downlods +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google-fusiontables2/enum.Result.html), should be +read by you to obtain the media. +If such a method also supports a [Response Result](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.ResponseResult.html), it will return that by default. +You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +this call: `.param("alt", "media")`. + +Methods supporting uploads can do so using up to 2 different protocols: +*simple* and *resumable*. The distinctiveness of each is represented by customized +`doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. + +## Customization and Callbacks + +You may alter the way an `doit()` method is called by providing a [delegate](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.CallBuilder.html) before making the final `doit()` call. +Respective methods will be called to provide progress information, as well as determine whether the system should +retry on failure. + +The [delegate trait](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. + +## Optional Parts in Server-Requests + +All structures provided by this library are made to be [enocodable](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +Most optionals are are considered [Parts](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.Part.html) which are identifyable by name, which will be sent to +the server to indicate either the set parts of the request or the desired parts in the response. + +## Builder Arguments + +Using [method builders](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +These will always take a single argument, for which the following statements are true. + +* [PODs][wiki-pod] are handed by copy +* strings are passed as `&str` +* [request values](http://byron.github.io/google-apis-rs/google-fusiontables2/trait.RequestValue.html) are borrowed + +Arguments will always be copied or cloned into the builder, to make them independent of their original life times. + +[wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +[builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +[google-go-api]: https://github.com/google/google-api-go-client + +# License +The **fusiontables2** library was generated by Sebastian Thiel, and is placed +under the *MIT* license. +You can read the full text at the repository's [license file][repo-license]. + +[repo-license]: https://github.com/Byron/google-apis-rs/LICENSE.md diff --git a/gen/fusiontables2/src/cmn.rs b/gen/fusiontables2/src/cmn.rs new file mode 100644 index 0000000000..aba4c1f9d1 --- /dev/null +++ b/gen/fusiontables2/src/cmn.rs @@ -0,0 +1,606 @@ +// COPY OF 'src/rust/cmn.rs' +// DO NOT EDIT +use std::marker::MarkerTrait; +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::thread::sleep; + +use mime::{Mime, TopLevel, SubLevel, Attr, Value}; +use oauth2::{TokenType, Retry, self}; +use hyper; +use hyper::header::{ContentType, ContentLength, Headers, UserAgent, Authorization, Header, + HeaderFormat}; +use hyper::http::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde; + +/// Identifies the Hub. There is only one per library, this trait is supposed +/// to make intended use more explicit. +/// The hub allows to access all resource methods more easily. +pub trait Hub: MarkerTrait {} + +/// Identifies types for building methods of a particular resource type +pub trait ResourceMethodsBuilder: MarkerTrait {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder: MarkerTrait {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource: MarkerTrait {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult: MarkerTrait {} + +/// Identifies types which are used in API requests. +pub trait RequestValue: MarkerTrait {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType: MarkerTrait {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part: MarkerTrait {} + +/// Identifies types which are only used by other types internally. +/// They have no special meaning, this trait just marks them for completeness. +pub trait NestedType: MarkerTrait {} + +/// A utility to specify reader types which provide seeking capabilities too +pub trait ReadSeek: Seek + Read {} +impl ReadSeek for T {} + +/// A trait for all types that can convert themselves into a *parts* string +pub trait ToParts { + fn to_parts(&self) -> String; +} + + +/// A utility type which can decode a server response that indicates error +#[derive(Deserialize)] +pub struct JsonServerError { + pub error: String, + pub error_description: Option +} + +#[derive(Copy, Clone)] +pub struct DummyNetworkStream; + +impl Read for DummyNetworkStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Ok(0) + } +} + +impl Write for DummyNetworkStream { + fn write(&mut self, _: &[u8]) -> io::Result { + Ok(0) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl hyper::net::NetworkStream for DummyNetworkStream { + fn peer_addr(&mut self) -> io::Result { + Ok("127.0.0.1:1337".parse().unwrap()) + } +} + + +/// A trait specifying functionality to help controlling any request performed by the API. +/// The trait has a conservative default implementation. +/// +/// It contains methods to deal with all common issues, as well with the ones related to +/// uploading media +pub trait Delegate { + + /// Called at the beginning of any API request. The delegate should store the method + /// information if he is interesting in knowing more context when further calls to it + /// are made. + /// The matching `finished()` call will always be made, no matter whether or not the API + /// request was sucessfull. That way, the delgate may easily maintain a clean state + /// between various API calls. + fn begin(&mut self, MethodInfo) {} + + /// Called whenever there is an [HttpError](http://hyperium.github.io/hyper/hyper/error/enum.HttpError.html), usually if there are network problems. + /// + /// Return retry information. + fn http_error(&mut self, &hyper::HttpError) -> Retry { + Retry::Abort + } + + /// Called whenever there is the need for your applications API key after + /// the official authenticator implementation didn't provide one, for some reason. + /// If this method returns None as well, the underlying operation will fail + fn api_key(&mut self) -> Option { + None + } + + /// Called whenever the Authenticator didn't yield a token. The delegate + /// may attempt to provide one, or just take is a general information about the + /// pending impending failure + fn token(&mut self) -> Option { + None + } + + /// Called during resumable uploads to provide a URL for the impending upload. + /// It was saved after a previous call to `store_upload_url(...)`, and if not None, + /// will be used instead of asking the server for a new upload URL. + /// This is useful in case a previous resumable upload was aborted/cancelled, but should now + /// be resumed. + /// The returned URL will be used exactly once - if it fails again and the delegate allows + /// to retry, we will ask the server for a new upload URL. + fn upload_url(&mut self) -> Option { + None + } + + /// Called after we have retrieved a new upload URL for a resumable upload to store it + /// in case we fail or cancel. That way, we can attempt to resume the upload later, + /// see `upload_url()`. + fn store_upload_url(&mut self, url: &str) { + let _ = url; + } + + /// Called whenever a server response could not be decoded from json. + /// It's for informational purposes only, the caller will return with an error + /// accordingly. + /// + /// # Arguments + /// + /// `json_encoded_value` - The json-encoded value which failed to decode. + /// `json_decode_error` - The decoder error + fn response_json_decode_error(&mut self, json_encoded_value: &str, json_decode_error: &serde::json::Error) { + let _ = json_encoded_value; + let _ = json_decode_error; + } + + /// Called whenever the http request returns with a non-success status code. + /// This can involve authentication issues, or anything else that very much + /// depends on the used API method. + /// The delegate should check the status, header and decoded json error to decide + /// whether to retry or not. In the latter case, the underlying call will fail. + fn http_failure(&mut self, _: &hyper::client::Response, Option) -> Retry { + Retry::Abort + } + + /// Called prior to sending the main request of the given method. It can be used to time + /// the call or to print progress information. + /// It's also useful as you can be sure that a request will definitely be made. + fn pre_request(&mut self) { } + + /// Return the size of each chunk of a resumable upload. + /// Must be a power of two, with 1<<18 being the smallest allowed chunk size. + /// Will be called once before starting any resumable upload. + fn chunk_size(&mut self) -> u64 { + 1 << 23 + } + + /// Called before the given chunk is uploaded to the server. + /// If true is returned, the upload will be interrupted. + /// However, it may be resumable if you stored the upload URL in a previous call + /// to `store_upload_url()` + fn cancel_chunk_upload(&mut self, chunk: &ContentRange) -> bool { + let _ = chunk; + false + } + + /// Called before the API request method returns, in every case. It can be used to clean up + /// internal state between calls to the API. + /// This call always has a matching call to `begin(...)`. + /// + /// # Arguments + /// + /// `is_success` - a true value indicates the operation was successful. If false, you should + /// discard all values stored during `store_upload_url`. + fn finished(&mut self, is_success: bool) { + let _ = is_success; + } +} + +/// A delegate with a conservative default implementation, which is used if no other delegate is +/// set. +#[derive(Default)] +pub struct DefaultDelegate; + +impl Delegate for DefaultDelegate {} + + +/// A universal result type used as return for all action method results. +pub enum Result { + /// The http connection failed + HttpError(hyper::HttpError), + + /// An attempt was made to upload a resource with size stored in field `.0` + /// even though the maximum upload size is what is stored in field `.1`. + UploadSizeLimitExceeded(u64, u64), + + /// We needed an API key for authentication, but didn't obtain one. + /// Neither through the authenticator, nor through the Delegate. + MissingAPIKey, + + /// We required a Token, but didn't get one from the Authenticator + MissingToken, + + /// The delgate instructed to cancel the operation + Cancelled, + + /// An additional, free form field clashed with one of the built-in optional ones + FieldClash(&'static str), + + /// Shows that we failed to decode the server response. + /// This can happen if the protocol changes in conjunction with strict json decoding. + JsonDecodeError(serde::json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), + + /// It worked ! + Success(T), +} + +/// Contains information about an API request. +pub struct MethodInfo { + pub id: &'static str, + pub http_method: Method, +} + +const BOUNDARY: &'static str = "MDuXWGyeE33QFXGchb2VFWc4Z7945d"; + +/// Provides a `Read` interface that converts multiple parts into the protocol +/// identified by [RFC2387](https://tools.ietf.org/html/rfc2387). +/// **Note**: This implementation is just as rich as it needs to be to perform uploads +/// to google APIs, and might not be a fully-featured implementation. +#[derive(Default)] +pub struct MultiPartReader<'a> { + raw_parts: Vec<(Headers, &'a mut Read)>, + current_part: Option<(Cursor>, &'a mut Read)>, + last_part_boundary: Option>>, +} + +impl<'a> MultiPartReader<'a> { + + /// Reserve memory for exactly the given amount of parts + pub fn reserve_exact(&mut self, cap: usize) { + self.raw_parts.reserve_exact(cap); + } + + /// Add a new part to the queue of parts to be read on the first `read` call. + /// + /// # Arguments + /// `headers` - identifying the body of the part. It's similar to the header + /// in an ordinary single-part call, and should thus contain the + /// same information. + /// `reader` - a reader providing the part's body + /// `size` - the amount of bytes provided by the reader. It will be put onto the header as + /// content-size. + /// `mime` - It will be put onto the content type + /// # Panics + /// + /// If this method is called after the first `read` call, it will panic + pub fn add_part(&mut self, reader: &'a mut Read, size: u64, mime_type: Mime) -> &mut MultiPartReader<'a> { + let mut headers = Headers::new(); + headers.set(ContentType(mime_type)); + headers.set(ContentLength(size)); + self.raw_parts.push((headers, reader)); + self + } + + /// Returns the mime-type representing our multi-part message. + /// Use it with the ContentType header. + pub fn mime_type(&self) -> Mime { + Mime( + TopLevel::Multipart, + SubLevel::Ext("Related".to_string()), + vec![(Attr::Ext("boundary".to_string()), Value::Ext(BOUNDARY.to_string()))], + ) + } + + /// Returns true if we are totally used + fn is_depleted(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_none() && self.last_part_boundary.is_none() + } + + /// Returns true if we are handling our last part + fn is_last_part(&self) -> bool { + self.raw_parts.len() == 0 && self.current_part.is_some() + } +} + +impl<'a> Read for MultiPartReader<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match (self.raw_parts.len(), + self.current_part.is_none(), + self.last_part_boundary.is_none()) { + (_, _, false) => { + let br = self.last_part_boundary.as_mut().unwrap().read(buf).unwrap_or(0); + if br < buf.len() { + self.last_part_boundary = None; + } + return Ok(br) + }, + (0, true, true) => return Ok(0), + (n, true, _) if n > 0 => { + let (headers, reader) = self.raw_parts.remove(0); + let mut c = Cursor::new(Vec::::new()); + write!(&mut c, "{}--{}{}{}{}", LINE_ENDING, BOUNDARY, LINE_ENDING, + headers, LINE_ENDING).unwrap(); + c.seek(SeekFrom::Start(0)).unwrap(); + self.current_part = Some((c, reader)); + } + _ => {}, + } + + // read headers as long as possible + let (hb, rr) = { + let &mut (ref mut c, ref mut reader) = self.current_part.as_mut().unwrap(); + let b = c.read(buf).unwrap_or(0); + (b, reader.read(&mut buf[b..])) + }; + + match rr { + Ok(bytes_read) => { + if hb < buf.len() && bytes_read == 0 { + if self.is_last_part() { + // before clearing the last part, we will add the boundary that + // will be written last + self.last_part_boundary = Some(Cursor::new( + format!("{}--{}", LINE_ENDING, BOUNDARY).into_bytes())) + } + // We are depleted - this can trigger the next part to come in + self.current_part = None; + } + let mut total_bytes_read = hb + bytes_read; + while total_bytes_read < buf.len() && !self.is_depleted() { + match self.read(&mut buf[total_bytes_read ..]) { + Ok(br) => total_bytes_read += br, + Err(err) => return Err(err), + } + } + Ok(total_bytes_read) + } + Err(err) => { + // fail permanently + self.current_part = None; + self.last_part_boundary = None; + self.raw_parts.clear(); + Err(err) + } + } + } +} + + +/// The `X-Upload-Content-Type` header. +#[derive(Clone, PartialEq, Debug)] +pub struct XUploadContentType(pub Mime); + +impl_header!(XUploadContentType, + "X-Upload-Content-Type", + Mime); + +#[derive(Clone, PartialEq, Debug)] +pub struct Chunk { + pub first: u64, + pub last: u64 +} + +impl fmt::Display for Chunk { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}-{}", self.first, self.last).ok(); + Ok(()) + } +} + +impl FromStr for Chunk { + type Err = &'static str; + + /// NOTE: only implements `%i-%i`, not `*` + fn from_str(s: &str) -> std::result::Result { + let parts: Vec<&str> = s.split('-').collect(); + if parts.len() != 2 { + return Err("Expected two parts: %i-%i") + } + Ok( + Chunk { + first: match FromStr::from_str(parts[0]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'first' as digit") + }, + last: match FromStr::from_str(parts[1]) { + Ok(d) => d, + _ => return Err("Couldn't parse 'last' as digit") + } + } + ) + } +} + +/// Implements the Content-Range header, for serialization only +#[derive(Clone, PartialEq, Debug)] +pub struct ContentRange { + pub range: Option, + pub total_length: u64, +} + +impl Header for ContentRange { + fn header_name() -> &'static str { + "Content-Range" + } + + /// We are not parsable, as parsing is done by the `Range` header + fn parse_header(_: &[Vec]) -> Option { + None + } +} + + +impl HeaderFormat for ContentRange { + fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + try!(fmt.write_str("bytes ")); + match self.range { + Some(ref c) => try!(c.fmt(fmt)), + None => try!(fmt.write_str("*")) + } + write!(fmt, "/{}", self.total_length).ok(); + Ok(()) + } +} + +#[derive(Clone, PartialEq, Debug)] +pub struct RangeResponseHeader(pub Chunk); + +impl Header for RangeResponseHeader { + fn header_name() -> &'static str { + "Range" + } + + fn parse_header(raw: &[Vec]) -> Option { + match raw { + [ref v] => { + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes="; + if s.starts_with(PREFIX) { + let c: Chunk = match FromStr::from_str(&s[PREFIX.len()..]) { + Ok(c) => c, + _ => return None + }; + return Some(RangeResponseHeader(c)) + } + } + None + }, + _ => None + } + } +} + +impl HeaderFormat for RangeResponseHeader { + /// No implmentation necessary, we just need to parse + fn fmt_header(&self, _: &mut fmt::Formatter) -> fmt::Result { + Err(fmt::Error) + } +} + +/// A utility type to perform a resumable upload from start to end. +pub struct ResumableUploadHelper<'a, NC: 'a, A: 'a> { + pub client: &'a mut hyper::client::Client, + pub delegate: &'a mut Delegate, + pub start_at: Option, + pub auth: &'a mut A, + pub user_agent: &'a str, + pub auth_header: Authorization, + pub url: &'a str, + pub reader: &'a mut ReadSeek, + pub media_type: Mime, + pub content_length: u64 +} + +impl<'a, NC, A> ResumableUploadHelper<'a, NC, A> + where NC: hyper::net::NetworkConnector, + A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> (Option, hyper::HttpResult) { + loop { + match self.client.post(self.url) + .header(UserAgent(self.user_agent.to_string())) + .header(ContentRange { range: None, total_length: self.content_length }) + .header(self.auth_header.clone()) + .send() { + Ok(r) => { + // 308 = resume-incomplete == PermanentRedirect + let headers = r.headers.clone(); + let h: &RangeResponseHeader = match headers.get() { + Some(hh) if r.status == StatusCode::PermanentRedirect => hh, + None|Some(_) => { + if let Retry::After(d) = self.delegate.http_failure(&r, None) { + sleep(d); + continue; + } + return (None, Ok(r)) + } + }; + return (Some(h.0.last), Ok(r)) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return (None, Err(err)) + } + } + } + } + + /// returns None if operation was cancelled by delegate, or the HttpResult. + /// It can be that we return the result just because we didn't understand the status code - + /// caller should check for status himself before assuming it's OK to use + pub fn upload(&mut self) -> Option> { + let mut start = match self.start_at { + Some(s) => s, + None => match self.query_transfer_status() { + (Some(s), _) => s, + (_, result) => return Some(result) + } + }; + + const MIN_CHUNK_SIZE: u64 = 1 << 18; + let chunk_size = match self.delegate.chunk_size() { + cs if cs > MIN_CHUNK_SIZE => cs, + _ => MIN_CHUNK_SIZE + }; + + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + let mut section_reader = self.reader.take(request_size); + let range_header = ContentRange { + range: Some(Chunk {first: start, last: start + request_size - 1}), + total_length: self.content_length + }; + start += request_size; + if self.delegate.cancel_chunk_upload(&range_header) { + return None + } + match self.client.post(self.url) + .header(range_header) + .header(ContentType(self.media_type.clone())) + .header(UserAgent(self.user_agent.to_string())) + .body(&mut section_reader) + .send() { + Ok(mut res) => { + if res.status == StatusCode::PermanentRedirect { + continue + } + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let Retry::After(d) = self.delegate.http_failure(&res, serde::json::from_str(&json_err).ok()) { + sleep(d); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep(d); + continue; + } + return Some(Err(err)) + } + } + } + } +} \ No newline at end of file diff --git a/gen/fusiontables2/src/lib.rs b/gen/fusiontables2/src/lib.rs new file mode 100644 index 0000000000..cf30ed357e --- /dev/null +++ b/gen/fusiontables2/src/lib.rs @@ -0,0 +1,10325 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *fusiontables* crate version *0.1.0+20141113*, where *20141113* is the exact revision of the *fusiontables:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.0*. +//! +//! Everything else about the *fusiontables* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/fusiontables). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/fusiontables2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Fusiontables.html) ... +//! +//! * [column](struct.Column.html) +//! * [*delete*](struct.ColumnDeleteCall.html), [*get*](struct.ColumnGetCall.html), [*insert*](struct.ColumnInsertCall.html), [*list*](struct.ColumnListCall.html), [*patch*](struct.ColumnPatchCall.html) and [*update*](struct.ColumnUpdateCall.html) +//! * query +//! * [*sql*](struct.QuerySqlCall.html) and [*sql get*](struct.QuerySqlGetCall.html) +//! * style +//! * [*delete*](struct.StyleDeleteCall.html), [*get*](struct.StyleGetCall.html), [*insert*](struct.StyleInsertCall.html), [*list*](struct.StyleListCall.html), [*patch*](struct.StylePatchCall.html) and [*update*](struct.StyleUpdateCall.html) +//! * [table](struct.Table.html) +//! * [*copy*](struct.TableCopyCall.html), [*delete*](struct.TableDeleteCall.html), [*get*](struct.TableGetCall.html), [*import rows*](struct.TableImportRowCall.html), [*import table*](struct.TableImportTableCall.html), [*insert*](struct.TableInsertCall.html), [*list*](struct.TableListCall.html), [*patch*](struct.TablePatchCall.html), [*replace rows*](struct.TableReplaceRowCall.html) and [*update*](struct.TableUpdateCall.html) +//! * [task](struct.Task.html) +//! * [*delete*](struct.TaskDeleteCall.html), [*get*](struct.TaskGetCall.html) and [*list*](struct.TaskListCall.html) +//! * [template](struct.Template.html) +//! * [*delete*](struct.TemplateDeleteCall.html), [*get*](struct.TemplateGetCall.html), [*insert*](struct.TemplateInsertCall.html), [*list*](struct.TemplateListCall.html), [*patch*](struct.TemplatePatchCall.html) and [*update*](struct.TemplateUpdateCall.html) +//! +//! +//! Upload supported by ... +//! +//! * [*replace rows table*](struct.TableReplaceRowCall.html) +//! * [*import rows table*](struct.TableImportRowCall.html) +//! * [*import table table*](struct.TableImportTableCall.html) +//! +//! Download supported by ... +//! +//! * [*sql get query*](struct.QuerySqlGetCall.html) +//! * [*sql query*](struct.QuerySqlCall.html) +//! +//! +//! +//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](../index.html). +//! +//! # Structure of this Library +//! +//! The API is structured into the following primary items: +//! +//! * **[Hub](struct.Fusiontables.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * **[Resources](trait.Resource.html)** +//! * primary types that you can apply *Activities* to +//! * a collection of properties and *Parts* +//! * **[Parts](trait.Part.html)** +//! * a collection of properties +//! * never directly used in *Activities* +//! * **[Activities](trait.CallBuilder.html)** +//! * operations to apply to *Resources* +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.table().import_table(...).doit() +//! let r = hub.table().patch(...).doit() +//! let r = hub.table().get(...).doit() +//! let r = hub.table().copy(...).doit() +//! let r = hub.table().insert(...).doit() +//! let r = hub.table().update(...).doit() +//! ``` +//! +//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` +//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be +//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired. +//! The `doit()` method performs the actual communication with the server and returns the respective result. +//! +//! # Usage +//! +//! ## Setting up your Project +//! +//! To use this library, you would put the following lines into your `Cargo.toml` file: +//! +//! ```toml +//! [dependencies] +//! google-fusiontables2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate "yup-oauth2" as oauth2; +//! extern crate "google-fusiontables2" as fusiontables2; +//! use fusiontables2::Result; +//! use std::fs; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use fusiontables2::Fusiontables; +//! +//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and +//! // `client_secret`, among other things. +//! let secret: ApplicationSecret = Default::default(); +//! // Instantiate the authenticator. It will choose a suitable authentication flow for you, +//! // unless you replace `None` with the desired Flow. +//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +//! // retrieve them from storage. +//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +//! hyper::Client::new(), +//! ::default(), None); +//! let mut hub = Fusiontables::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `upload_resumable(...)`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.table().import_table("name") +//! .encoding("et") +//! .delimiter("dolores") +//! .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +//! +//! match result { +//! Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +//! Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +//! Result::MissingToken => println!("OAuth2: Missing Token"), +//! Result::Cancelled => println!("Operation cancelled by user"), +//! Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +//! Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +//! Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +//! Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +//! Result::Success(_) => println!("Success (value doesn't print)"), +//! } +//! # } +//! ``` +//! ## Handling Errors +//! +//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of +//! the doit() methods, or handed as possibly intermediate results to either the +//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](../yup-oauth2/trait.AuthenticatorDelegate.html). +//! +//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This +//! makes the system potentially resilient to all kinds of errors. +//! +//! ## Uploads and Downlods +//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be +//! read by you to obtain the media. +//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default. +//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making +//! this call: `.param("alt", "media")`. +//! +//! Methods supporting uploads can do so using up to 2 different protocols: +//! *simple* and *resumable*. The distinctiveness of each is represented by customized +//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively. +//! +//! ## Customization and Callbacks +//! +//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the +//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call. +//! Respective methods will be called to provide progress information, as well as determine whether the system should +//! retry on failure. +//! +//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort. +//! +//! ## Optional Parts in Server-Requests +//! +//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and +//! [decodable](trait.ResponseResult.html) via json. Optionals are used to indicate that partial requests are responses are valid. +//! Most optionals are are considered [Parts](trait.Part.html) which are identifyable by name, which will be sent to +//! the server to indicate either the set parts of the request or the desired parts in the response. +//! +//! ## Builder Arguments +//! +//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods. +//! These will always take a single argument, for which the following statements are true. +//! +//! * [PODs][wiki-pod] are handed by copy +//! * strings are passed as `&str` +//! * [request values](trait.RequestValue.html) are borrowed +//! +//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times. +//! +//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure +//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern +//! [google-go-api]: https://github.com/google/google-api-go-client +//! +//! +#![feature(core,io,thread_sleep)] +// Unused attributes happen thanks to defined, but unused structures +// We don't warn about this, as depending on the API, some data structures or facilities are never used. +// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any +// unused imports in fully featured APIs. Same with unused_mut ... . +#![allow(unused_imports, unused_mut, dead_code)] +// Required for serde annotations +#![feature(custom_derive, custom_attribute, plugin)] +#![plugin(serde_macros)] + +#[macro_use] +extern crate hyper; +extern crate serde; +extern crate "yup-oauth2" as oauth2; +extern crate mime; +extern crate url; + +mod cmn; + +use std::collections::HashMap; +use std::cell::RefCell; +use std::borrow::BorrowMut; +use std::default::Default; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use serde::json; +use std::io; +use std::fs; +use std::thread::sleep; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, ResourceMethodsBuilder, Resource, JsonServerError}; + + +// ############## +// UTILITIES ### +// ############ + +/// Identifies the an OAuth2 authorization scope. +/// A scope is needed when requesting an +/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). +#[derive(PartialEq, Eq, Hash)] +pub enum Scope { + /// Manage your Fusion Tables + Full, + + /// View your Fusion Tables + Readonly, +} + +impl Str for Scope { + fn as_slice(&self) -> &str { + match *self { + Scope::Full => "https://www.googleapis.com/auth/fusiontables", + Scope::Readonly => "https://www.googleapis.com/auth/fusiontables.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Readonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Fusiontables related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate "yup-oauth2" as oauth2; +/// extern crate "google-fusiontables2" as fusiontables2; +/// use fusiontables2::Result; +/// use std::fs; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use fusiontables2::Fusiontables; +/// +/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and +/// // `client_secret`, among other things. +/// let secret: ApplicationSecret = Default::default(); +/// // Instantiate the authenticator. It will choose a suitable authentication flow for you, +/// // unless you replace `None` with the desired Flow. +/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about +/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and +/// // retrieve them from storage. +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Fusiontables::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `upload_resumable(...)`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.table().import_table("name") +/// .encoding("accusam") +/// .delimiter("takimata") +/// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); +/// +/// match result { +/// Result::HttpError(err) => println!("HTTPERROR: {:?}", err), +/// Result::MissingAPIKey => println!("Auth: Missing API Key - used if there are no scopes"), +/// Result::MissingToken => println!("OAuth2: Missing Token"), +/// Result::Cancelled => println!("Operation cancelled by user"), +/// Result::UploadSizeLimitExceeded(size, max_size) => println!("Upload size too big: {} of {}", size, max_size), +/// Result::Failure(_) => println!("General Failure (hyper::client::Response doesn't print)"), +/// Result::FieldClash(clashed_field) => println!("You added custom parameter which is part of builder: {:?}", clashed_field), +/// Result::JsonDecodeError(err) => println!("Couldn't understand server reply - maybe API needs update: {:?}", err), +/// Result::Success(_) => println!("Success (value doesn't print)"), +/// } +/// # } +/// ``` +pub struct Fusiontables { + client: RefCell, + auth: RefCell, + _user_agent: String, + + _m: PhantomData +} + +impl<'a, C, NC, A> Hub for Fusiontables {} + +impl<'a, C, NC, A> Fusiontables + where NC: hyper::net::NetworkConnector, C: BorrowMut>, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Fusiontables { + Fusiontables { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.0".to_string(), + _m: PhantomData + } + } + + pub fn column(&'a self) -> ColumnMethods<'a, C, NC, A> { + ColumnMethods { hub: &self } + } + pub fn query(&'a self) -> QueryMethods<'a, C, NC, A> { + QueryMethods { hub: &self } + } + pub fn style(&'a self) -> StyleMethods<'a, C, NC, A> { + StyleMethods { hub: &self } + } + pub fn table(&'a self) -> TableMethods<'a, C, NC, A> { + TableMethods { hub: &self } + } + pub fn task(&'a self) -> TaskMethods<'a, C, NC, A> { + TaskMethods { hub: &self } + } + pub fn template(&'a self) -> TemplateMethods<'a, C, NC, A> { + TemplateMethods { hub: &self } + } + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.0`. + /// + /// Returns the previously set user-agent. + pub fn user_agent(&mut self, agent_name: String) -> String { + let prev = self._user_agent.clone(); + self._user_agent = agent_name; + prev + } +} + + +// ############ +// SCHEMAS ### +// ########## +/// A background task on a table, initiated for time and or resource consuming operations such as a column type change or delete all rows operation. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get task](struct.TaskGetCall.html) (response) +/// * [replace rows table](struct.TableReplaceRowCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Task { + /// True if the task is in progress, its progress indicator will indicated where it is, and it can't be deleted. + pub started: bool, + /// Task percentage completion. + pub progress: String, + /// Type name: a template for an individual task. + pub kind: String, + /// The type of task being executed in the background. + #[serde(alias="type")] + pub type_: String, + /// Identifier for the task. + #[serde(alias="taskId")] + pub task_id: String, +} + +impl ResponseResult for Task {} + + +/// Specifies the details of a column in a table. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get column](struct.ColumnGetCall.html) (response) +/// * [update column](struct.ColumnUpdateCall.html) (request|response) +/// * [insert column](struct.ColumnInsertCall.html) (request|response) +/// * [patch column](struct.ColumnPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Column { + /// Column graph predicate. + /// Used to map table to graph data model (subject,predicate,object) + /// See http://www.w3.org/TR/2014/REC-rdf11-concepts-20140225/#data-model + #[serde(alias="graphPredicate")] + pub graph_predicate: Option, + /// Type name: a template for an individual column. + pub kind: Option, + /// List of valid values used to validate data and supply a drop-down list of values in the web application. + #[serde(alias="validValues")] + pub valid_values: Option>, + /// Column description. + pub description: Option, + /// Identifier of the base column. If present, this column is derived from the specified base column. + #[serde(alias="baseColumn")] + pub base_column: Option, + /// Identifier for the column. + #[serde(alias="columnId")] + pub column_id: Option, + /// JSON object containing custom column properties. + #[serde(alias="columnPropertiesJson")] + pub column_properties_json: Option, + /// Format pattern. + #[serde(alias="formatPattern")] + pub format_pattern: Option, + /// JSON schema for interpreting JSON in this column. + #[serde(alias="columnJsonSchema")] + pub column_json_schema: Option, + /// Type of the column. + #[serde(alias="type")] + pub type_: Option, + /// If true, data entered via the web application is validated. + #[serde(alias="validateData")] + pub validate_data: Option, + /// Name of the column. + pub name: Option, +} + +impl RequestValue for Column {} +impl ResponseResult for Column {} + + +/// Specifies the minimum and maximum values, the color, opacity, icon and weight of a bucket within a StyleSetting. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Bucket { + /// Opacity of the color: 0.0 (transparent) to 1.0 (opaque). + pub opacity: f64, + /// Width of a line (in pixels). + pub weight: i32, + /// Minimum value in the selected column for a row to be styled according to the bucket color, opacity, icon, or weight. + pub min: f64, + /// Color of line or the interior of a polygon in #RRGGBB format. + pub color: String, + /// Maximum value in the selected column for a row to be styled according to the bucket color, opacity, icon, or weight. + pub max: f64, + /// Icon name used for a point. + pub icon: String, +} + +impl Part for Bucket {} + + +/// Represents a StyleFunction within a StyleSetting +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StyleFunction { + /// Gradient function that interpolates a range of colors based on column value. + pub gradient: StyleFunctionGradient, + /// Name of the column whose value is used in the style. + #[serde(alias="columnName")] + pub column_name: String, + /// Bucket function that assigns a style based on the range a column value falls into. + pub buckets: Vec, + /// Stylers can be one of three kinds: "fusiontables#fromColumn" if the column value is to be used as is, i.e., the column values can have colors in #RRGGBBAA format or integer line widths or icon names; "fusiontables#gradient" if the styling of the row is to be based on applying the gradient function on the column value; or "fusiontables#buckets" if the styling is to based on the bucket into which the the column value falls. + pub kind: String, +} + +impl Part for StyleFunction {} + + +/// Represents a list of tasks in a table. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list task](struct.TaskListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TaskList { + /// Token used to access the next page of this result. No token is displayed if there are no more tokens left. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of all requested tasks. + pub items: Vec, + /// Type name: a list of all tasks. + pub kind: String, + /// Total number of tasks for the table. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for TaskList {} + + +/// Gradient function that interpolates a range of colors based on column value. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StyleFunctionGradient { + /// Higher-end of the interpolation range: rows with this value will be assigned to colors[n-1]. + pub max: f64, + /// Array with two or more colors. + pub colors: Vec, + /// Lower-end of the interpolation range: rows with this value will be assigned to colors[0]. + pub min: f64, +} + +impl NestedType for StyleFunctionGradient {} +impl Part for StyleFunctionGradient {} + + +/// Represents the contents of InfoWindow templates. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [get template](struct.TemplateGetCall.html) (response) +/// * [update template](struct.TemplateUpdateCall.html) (request|response) +/// * [insert template](struct.TemplateInsertCall.html) (request|response) +/// * [patch template](struct.TemplatePatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Template { + /// Body of the template. It contains HTML with {column_name} to insert values from a particular column. The body is sanitized to remove certain tags, e.g., script. Only one of body or automaticColumns can be specified. + pub body: Option, + /// Type name: a template for the info window contents. The template can either include an HTML body or a list of columns from which the template is computed automatically. + pub kind: Option, + /// Identifier for the table for which the template is defined. + #[serde(alias="tableId")] + pub table_id: Option, + /// Optional name assigned to a template. + pub name: Option, + /// Identifier for the template, unique within the context of a particular table. + #[serde(alias="templateId")] + pub template_id: Option, + /// List of columns from which the template is to be automatically constructed. Only one of body or automaticColumns can be specified. + #[serde(alias="automaticColumnNames")] + pub automatic_column_names: Option>, +} + +impl RequestValue for Template {} +impl ResponseResult for Template {} + + +/// Identifier of the base column. If present, this column is derived from the specified base column. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ColumnBaseColumn { + /// Offset to the entry in the list of base tables in the table definition. + #[serde(alias="tableIndex")] + pub table_index: i32, + /// The id of the column in the base table from which this column is derived. + #[serde(alias="columnId")] + pub column_id: i32, +} + +impl NestedType for ColumnBaseColumn {} +impl Part for ColumnBaseColumn {} + + +/// Represents a list of columns in a table. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list column](struct.ColumnListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct ColumnList { + /// Token used to access the next page of this result. No token is displayed if there are no more tokens left. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of all requested columns. + pub items: Vec, + /// Type name: a list of all columns. + pub kind: String, + /// Total number of columns for the table. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for ColumnList {} + + +/// Represents an import request. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [import rows table](struct.TableImportRowCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Import { + /// The number of rows received from the import request. + #[serde(alias="numRowsReceived")] + pub num_rows_received: String, + /// Type name: a template for an import request. + pub kind: String, +} + +impl ResponseResult for Import {} + + +/// Represents a LineStyle within a StyleSetting +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LineStyle { + /// Width of the line in pixels. + #[serde(alias="strokeWeight")] + pub stroke_weight: i32, + /// Column-value or bucket styler that is used to determine the width of the line. + #[serde(alias="strokeWeightStyler")] + pub stroke_weight_styler: StyleFunction, + /// Color of the line in #RRGGBB format. + #[serde(alias="strokeColor")] + pub stroke_color: String, + /// Opacity of the line : 0.0 (transparent) to 1.0 (opaque). + #[serde(alias="strokeOpacity")] + pub stroke_opacity: f64, + /// Column-value, gradient or buckets styler that is used to determine the line color and opacity. + #[serde(alias="strokeColorStyler")] + pub stroke_color_styler: StyleFunction, +} + +impl Part for LineStyle {} + + +/// Represents a PolygonStyle within a StyleSetting +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PolygonStyle { + /// Column-value, gradient or buckets styler that is used to determine the border color and opacity. + #[serde(alias="strokeColorStyler")] + pub stroke_color_styler: StyleFunction, + /// Width of the polyon border in pixels. + #[serde(alias="strokeWeight")] + pub stroke_weight: i32, + /// Opacity of the polygon border: 0.0 (transparent) to 1.0 (opaque). + #[serde(alias="strokeOpacity")] + pub stroke_opacity: f64, + /// Column-value or bucket styler that is used to determine the width of the polygon border. + #[serde(alias="strokeWeightStyler")] + pub stroke_weight_styler: StyleFunction, + /// Column-value, gradient, or bucket styler that is used to determine the interior color and opacity of the polygon. + #[serde(alias="fillColorStyler")] + pub fill_color_styler: StyleFunction, + /// Color of the interior of the polygon in #RRGGBB format. + #[serde(alias="fillColor")] + pub fill_color: String, + /// Color of the polygon border in #RRGGBB format. + #[serde(alias="strokeColor")] + pub stroke_color: String, + /// Opacity of the interior of the polygon: 0.0 (transparent) to 1.0 (opaque). + #[serde(alias="fillOpacity")] + pub fill_opacity: f64, +} + +impl Part for PolygonStyle {} + + +/// Represents a list of styles for a given table. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list style](struct.StyleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct StyleSettingList { + /// Token used to access the next page of this result. No token is displayed if there are no more styles left. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// All requested style settings. + pub items: Vec, + /// Type name: in this case, a list of style settings. + pub kind: String, + /// Total number of styles for the table. + #[serde(alias="totalItems")] + pub total_items: i32, +} + +impl ResponseResult for StyleSettingList {} + + +/// Represents a response to an sql statement. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [sql get query](struct.QuerySqlGetCall.html) (response) +/// * [sql query](struct.QuerySqlCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct Sqlresponse { + /// Type name: a template for an individual table. + pub kind: String, + /// The rows in the table. For each cell we print out whatever cell value (e.g., numeric, string) exists. Thus it is important that each cell contains only one value. + pub rows: Vec>, + /// Columns in the table. + pub columns: Vec, +} + +impl ResponseResult for Sqlresponse {} + + +/// Represents a PointStyle within a StyleSetting +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PointStyle { + /// Column or a bucket value from which the icon name is to be determined. + #[serde(alias="iconStyler")] + pub icon_styler: StyleFunction, + /// Name of the icon. Use values defined in http://www.google.com/fusiontables/DataSource?dsrcid=308519 + #[serde(alias="iconName")] + pub icon_name: String, +} + +impl Part for PointStyle {} + + +/// Represents a complete StyleSettings object. The primary key is a combination of the tableId and a styleId. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [patch style](struct.StylePatchCall.html) (request|response) +/// * [get style](struct.StyleGetCall.html) (response) +/// * [update style](struct.StyleUpdateCall.html) (request|response) +/// * [insert style](struct.StyleInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StyleSetting { + /// Style definition for points in the table. + #[serde(alias="markerOptions")] + pub marker_options: Option, + /// Type name: an individual style setting. A StyleSetting contains the style defintions for points, lines, and polygons in a table. Since a table can have any one or all of them, a style definition can have point, line and polygon style definitions. + pub kind: Option, + /// Identifier for the table. + #[serde(alias="tableId")] + pub table_id: Option, + /// Optional name for the style setting. + pub name: Option, + /// Style definition for polygons in the table. + #[serde(alias="polygonOptions")] + pub polygon_options: Option, + /// Style definition for lines in the table. + #[serde(alias="polylineOptions")] + pub polyline_options: Option, + /// Identifier for the style setting (unique only within tables). + #[serde(alias="styleId")] + pub style_id: Option, +} + +impl RequestValue for StyleSetting {} +impl ResponseResult for StyleSetting {} + + +/// Represents a list of tables. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list table](struct.TableListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TableList { + /// Token used to access the next page of this result. No token is displayed if there are no more tokens left. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of all requested tables. + pub items: Vec, + /// Type name: a list of all tables. + pub kind: String, +} + +impl ResponseResult for TableList {} + + +/// Represents a list of templates for a given table. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [list template](struct.TemplateListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Deserialize)] +pub struct TemplateList { + /// Token used to access the next page of this result. No token is displayed if there are no more tokens left. + #[serde(alias="nextPageToken")] + pub next_page_token: String, + /// List of all requested templates. + pub items: Vec